veloren_voxygen/hud/
trade.rs

1use conrod_core::{
2    Color, Colorable, Labelable, Positionable, Sizeable, UiCell, Widget, WidgetCommon, color,
3    position::Relative,
4    widget::{self, Button, Image, Rectangle, State as ConrodState, Text, TextEdit},
5    widget_ids,
6};
7use specs::Entity as EcsEntity;
8use vek::*;
9
10use client::Client;
11use common::{
12    comp::{
13        Inventory, Stats,
14        inventory::item::{ItemDesc, ItemI18n, MaterialStatManifest, Quality},
15    },
16    recipe::RecipeBookManifest,
17    trade::{PendingTrade, SitePrices, TradeAction, TradePhase},
18};
19use common_net::sync::WorldSyncExt;
20use i18n::Localization;
21
22use crate::{
23    hud::{
24        Event as HudEvent, PromptDialogSettings,
25        bag::{BackgroundIds, InventoryScroller},
26    },
27    ui::{
28        ImageFrame, ItemTooltip, ItemTooltipManager, ItemTooltipable, Tooltip, TooltipManager,
29        Tooltipable,
30        fonts::Fonts,
31        slot::{ContentSize, SlotMaker},
32    },
33};
34
35use super::{
36    Hud, HudInfo, Show, TEXT_COLOR, TEXT_GRAY_COLOR, TradeAmountInput, UI_HIGHLIGHT_0, UI_MAIN,
37    img_ids::{Imgs, ImgsRot},
38    item_imgs::ItemImgs,
39    slots::{SlotKind, SlotManager, TradeSlot},
40    util,
41};
42use std::borrow::Cow;
43
44#[allow(clippy::large_enum_variant)]
45pub enum TradeEvent {
46    TradeAction(TradeAction),
47    SetDetailsMode(bool),
48    HudUpdate(HudUpdate),
49    ShowPrompt(PromptDialogSettings),
50}
51
52#[derive(Debug)]
53pub enum HudUpdate {
54    Focus(widget::Id),
55    Submit,
56}
57
58pub struct State {
59    ids: Ids,
60    bg_ids: BackgroundIds,
61}
62
63widget_ids! {
64    pub struct Ids {
65        trade_close,
66        bg,
67        bg_frame,
68        trade_title_bg,
69        trade_title,
70        inv_alignment[],
71        inv_slots[],
72        inv_textslots[],
73        offer_headers[],
74        accept_indicators[],
75        phase_indicator,
76        accept_button,
77        decline_button,
78        inventory_scroller,
79        amount_bg,
80        amount_notice,
81        amount_open_label,
82        amount_open_btn,
83        amount_open_ovlay,
84        amount_input,
85        amount_btn,
86        trade_details_btn,
87    }
88}
89
90#[derive(WidgetCommon)]
91pub struct Trade<'a> {
92    client: &'a Client,
93    info: &'a HudInfo,
94    imgs: &'a Imgs,
95    item_imgs: &'a ItemImgs,
96    fonts: &'a Fonts,
97    rot_imgs: &'a ImgsRot,
98    tooltip_manager: &'a mut TooltipManager,
99    item_tooltip_manager: &'a mut ItemTooltipManager,
100    #[conrod(common_builder)]
101    common: widget::CommonBuilder,
102    slot_manager: &'a mut SlotManager,
103    localized_strings: &'a Localization,
104    item_i18n: &'a ItemI18n,
105    msm: &'a MaterialStatManifest,
106    rbm: &'a RecipeBookManifest,
107    pulse: f32,
108    show: &'a mut Show,
109    needs_thirdconfirm: bool,
110}
111
112impl<'a> Trade<'a> {
113    pub fn new(
114        client: &'a Client,
115        info: &'a HudInfo,
116        imgs: &'a Imgs,
117        item_imgs: &'a ItemImgs,
118        fonts: &'a Fonts,
119        rot_imgs: &'a ImgsRot,
120        tooltip_manager: &'a mut TooltipManager,
121        item_tooltip_manager: &'a mut ItemTooltipManager,
122        slot_manager: &'a mut SlotManager,
123        localized_strings: &'a Localization,
124        item_i18n: &'a ItemI18n,
125        msm: &'a MaterialStatManifest,
126        rbm: &'a RecipeBookManifest,
127        pulse: f32,
128        show: &'a mut Show,
129    ) -> Self {
130        Self {
131            client,
132            info,
133            imgs,
134            item_imgs,
135            fonts,
136            rot_imgs,
137            tooltip_manager,
138            item_tooltip_manager,
139            common: widget::CommonBuilder::default(),
140            slot_manager,
141            localized_strings,
142            item_i18n,
143            msm,
144            rbm,
145            pulse,
146            show,
147            needs_thirdconfirm: false,
148        }
149    }
150}
151
152const MAX_TRADE_SLOTS: usize = 16;
153
154impl<'a> Trade<'a> {
155    fn background(&mut self, state: &mut ConrodState<'_, State>, ui: &mut UiCell<'_>) {
156        Image::new(self.imgs.inv_middle_bg_bag)
157            .w_h(424.0, 482.0)
158            .color(Some(UI_MAIN))
159            .mid_bottom_with_margin_on(ui.window, 295.0)
160            .set(state.ids.bg, ui);
161        Image::new(self.imgs.inv_middle_frame)
162            .w_h(424.0, 482.0)
163            .middle_of(state.ids.bg)
164            .color(Some(UI_HIGHLIGHT_0))
165            .set(state.ids.bg_frame, ui);
166    }
167
168    fn title(&mut self, state: &mut ConrodState<'_, State>, ui: &mut UiCell<'_>) {
169        Text::new(&self.localized_strings.get_msg("hud-trade-trade_window"))
170            .mid_top_with_margin_on(state.ids.bg_frame, 9.0)
171            .font_id(self.fonts.cyri.conrod_id)
172            .font_size(self.fonts.cyri.scale(20))
173            .color(Color::Rgba(0.0, 0.0, 0.0, 1.0))
174            .set(state.ids.trade_title_bg, ui);
175        Text::new(&self.localized_strings.get_msg("hud-trade-trade_window"))
176            .top_left_with_margins_on(state.ids.trade_title_bg, 2.0, 2.0)
177            .font_id(self.fonts.cyri.conrod_id)
178            .font_size(self.fonts.cyri.scale(20))
179            .color(TEXT_COLOR)
180            .set(state.ids.trade_title, ui);
181    }
182
183    fn phase_indicator(
184        &mut self,
185        state: &mut ConrodState<'_, State>,
186        ui: &mut UiCell<'_>,
187        trade: &'a PendingTrade,
188    ) {
189        let phase_text = match trade.phase() {
190            TradePhase::Mutate => self
191                .localized_strings
192                .get_msg("hud-trade-phase1_description"),
193            TradePhase::Review => self
194                .localized_strings
195                .get_msg("hud-trade-phase2_description"),
196            TradePhase::Complete => self
197                .localized_strings
198                .get_msg("hud-trade-phase3_description"),
199        };
200
201        Text::new(&phase_text)
202            .mid_top_with_margin_on(state.ids.bg, 70.0)
203            .font_id(self.fonts.cyri.conrod_id)
204            .font_size(self.fonts.cyri.scale(20))
205            .color(Color::Rgba(1.0, 1.0, 1.0, 1.0))
206            .set(state.ids.phase_indicator, ui);
207    }
208
209    fn item_pane(
210        &mut self,
211        state: &mut ConrodState<'_, State>,
212        ui: &mut UiCell<'_>,
213        trade: &'a PendingTrade,
214        prices: &'a Option<SitePrices>,
215        ours: bool,
216    ) -> Option<TradeEvent> {
217        let mut event = None;
218        let inventories = self.client.inventories();
219        let check_if_us = |who: usize| -> Option<_> {
220            let uid = trade.parties[who];
221            let entity = self.client.state().ecs().entity_from_uid(uid)?;
222            let is_ours = entity == self.client.entity();
223            Some(((who, uid, entity), is_ours))
224        };
225        let (who, uid, entity) = match check_if_us(0)? {
226            (x, is_ours) if ours == is_ours => x,
227            _ => check_if_us(1)?.0,
228        };
229        // TODO: update in accordance with https://gitlab.com/veloren/veloren/-/issues/960
230        let inventory = inventories.get(entity)?;
231        // Get our inventory to use it in item tooltips
232        // Our inventory is needed to know what recipes are known
233        let our_inventory = if entity == self.client.entity() {
234            inventory
235        } else {
236            let uid = trade.parties[if who == 0 { 1 } else { 0 }];
237            let entity = self.client.state().ecs().entity_from_uid(uid)?;
238            inventories.get(entity)?
239        };
240
241        // Alignment for Grid
242        let mut alignment = Rectangle::fill_with([200.0, 180.0], color::TRANSPARENT);
243        if !ours {
244            alignment = alignment.top_left_with_margins_on(state.ids.bg, 180.0, 32.5);
245        } else {
246            alignment = alignment.right_from(state.ids.inv_alignment[1 - who], 0.0);
247        }
248        alignment
249            .scroll_kids_vertically()
250            .set(state.ids.inv_alignment[who], ui);
251
252        let name = self
253            .client
254            .player_list()
255            .get(&uid)
256            .map(|info| info.player_alias.clone())
257            .or_else(|| {
258                self.client
259                    .state()
260                    .read_storage::<Stats>()
261                    .get(entity)
262                    .map(|e| e.name.to_owned())
263            })
264            .unwrap_or_else(|| format!("Player {}", who));
265
266        let offer_header = if ours {
267            self.localized_strings.get_msg("hud-trade-your_offer")
268        } else {
269            self.localized_strings.get_msg("hud-trade-their_offer")
270        };
271
272        Text::new(&offer_header)
273            .up_from(state.ids.inv_alignment[who], 20.0)
274            .font_id(self.fonts.cyri.conrod_id)
275            .font_size(self.fonts.cyri.scale(20))
276            .color(Color::Rgba(1.0, 1.0, 1.0, 1.0))
277            .set(state.ids.offer_headers[who], ui);
278
279        let has_accepted = trade.accept_flags[who];
280        let accept_indicator =
281            self.localized_strings
282                .get_msg_ctx("hud-trade-has_accepted", &i18n::fluent_args! {
283                    "playername" => &name,
284                });
285        Text::new(&accept_indicator)
286            .down_from(state.ids.inv_alignment[who], 50.0)
287            .font_id(self.fonts.cyri.conrod_id)
288            .font_size(self.fonts.cyri.scale(20))
289            .color(Color::Rgba(
290                1.0,
291                1.0,
292                1.0,
293                if has_accepted { 1.0 } else { 0.0 },
294            ))
295            .set(state.ids.accept_indicators[who], ui);
296
297        let mut invslots: Vec<_> = trade.offers[who].iter().map(|(k, v)| (*k, *v)).collect();
298        invslots.sort();
299        let tradeslots: Vec<_> = invslots
300            .into_iter()
301            .enumerate()
302            .map(|(index, (k, quantity))| TradeSlot {
303                index,
304                quantity,
305                invslot: Some(k),
306                ours,
307                entity,
308            })
309            .collect();
310
311        if matches!(trade.phase(), TradePhase::Mutate) {
312            event = self
313                .phase1_itemwidget(
314                    state,
315                    ui,
316                    inventory,
317                    our_inventory,
318                    who,
319                    ours,
320                    entity,
321                    name,
322                    prices,
323                    &tradeslots,
324                )
325                .or(event);
326        } else {
327            self.phase2_itemwidget(state, ui, inventory, who, ours, entity, &tradeslots);
328        }
329
330        event
331    }
332
333    fn phase1_itemwidget(
334        &mut self,
335        state: &mut ConrodState<'_, State>,
336        ui: &mut UiCell<'_>,
337        inventory: &Inventory,
338        // Used for item tooltip
339        our_inventory: &Inventory,
340        who: usize,
341        ours: bool,
342        entity: EcsEntity,
343        name: String,
344        prices: &'a Option<SitePrices>,
345        tradeslots: &[TradeSlot],
346    ) -> Option<TradeEvent> {
347        let mut event = None;
348        // Tooltips
349        let item_tooltip = ItemTooltip::new(
350            {
351                // Edge images [t, b, r, l]
352                // Corner images [tr, tl, br, bl]
353                let edge = &self.rot_imgs.tt_side;
354                let corner = &self.rot_imgs.tt_corner;
355                ImageFrame::new(
356                    [edge.cw180, edge.none, edge.cw270, edge.cw90],
357                    [corner.none, corner.cw270, corner.cw90, corner.cw180],
358                    Color::Rgba(0.08, 0.07, 0.04, 1.0),
359                    5.0,
360                )
361            },
362            self.client,
363            self.info,
364            self.imgs,
365            self.item_imgs,
366            self.pulse,
367            self.msm,
368            self.rbm,
369            Some(our_inventory),
370            self.localized_strings,
371            self.item_i18n,
372        )
373        .title_font_size(self.fonts.cyri.scale(20))
374        .parent(ui.window)
375        .desc_font_size(self.fonts.cyri.scale(12))
376        .font_id(self.fonts.cyri.conrod_id)
377        .desc_text_color(TEXT_COLOR);
378
379        if !ours {
380            InventoryScroller::new(
381                self.client,
382                self.imgs,
383                self.item_imgs,
384                self.fonts,
385                self.item_tooltip_manager,
386                self.slot_manager,
387                self.pulse,
388                self.localized_strings,
389                self.item_i18n,
390                false,
391                true,
392                false,
393                &item_tooltip,
394                name,
395                entity,
396                false,
397                inventory,
398                &state.bg_ids,
399                false,
400                self.show.trade_details,
401            )
402            .set(state.ids.inventory_scroller, ui);
403
404            let bag_tooltip = Tooltip::new({
405                // Edge images [t, b, r, l]
406                // Corner images [tr, tl, br, bl]
407                let edge = &self.rot_imgs.tt_side;
408                let corner = &self.rot_imgs.tt_corner;
409                ImageFrame::new(
410                    [edge.cw180, edge.none, edge.cw270, edge.cw90],
411                    [corner.none, corner.cw270, corner.cw90, corner.cw180],
412                    Color::Rgba(0.08, 0.07, 0.04, 1.0),
413                    5.0,
414                )
415            })
416            .title_font_size(self.fonts.cyri.scale(15))
417            .parent(ui.window)
418            .desc_font_size(self.fonts.cyri.scale(12))
419            .font_id(self.fonts.cyri.conrod_id)
420            .desc_text_color(TEXT_COLOR);
421
422            let buttons_top = 53.0;
423            let (txt, btn, hover, press) = if self.show.trade_details {
424                (
425                    "Grid mode",
426                    self.imgs.grid_btn,
427                    self.imgs.grid_btn_hover,
428                    self.imgs.grid_btn_press,
429                )
430            } else {
431                (
432                    "List mode",
433                    self.imgs.list_btn,
434                    self.imgs.list_btn_hover,
435                    self.imgs.list_btn_press,
436                )
437            };
438            let details_btn = Button::image(btn)
439                .w_h(32.0, 17.0)
440                .hover_image(hover)
441                .press_image(press);
442            if details_btn
443                .mid_top_with_margin_on(state.bg_ids.bg_frame, buttons_top)
444                .with_tooltip(self.tooltip_manager, txt, "", &bag_tooltip, TEXT_COLOR)
445                .set(state.ids.trade_details_btn, ui)
446                .was_clicked()
447            {
448                event = Some(TradeEvent::SetDetailsMode(!self.show.trade_details));
449            }
450        }
451
452        let mut slot_maker = SlotMaker {
453            empty_slot: self.imgs.inv_slot,
454            filled_slot: self.imgs.inv_slot,
455            selected_slot: self.imgs.inv_slot_sel,
456            background_color: Some(UI_MAIN),
457            content_size: ContentSize {
458                width_height_ratio: 1.0,
459                max_fraction: 0.75,
460            },
461            selected_content_scale: 1.067,
462            amount_font: self.fonts.cyri.conrod_id,
463            amount_margins: Vec2::new(-4.0, 0.0),
464            amount_font_size: self.fonts.cyri.scale(12),
465            amount_text_color: TEXT_COLOR,
466            content_source: inventory,
467            image_source: self.item_imgs,
468            slot_manager: Some(self.slot_manager),
469            pulse: self.pulse,
470        };
471
472        if state.ids.inv_slots.len() < 2 * MAX_TRADE_SLOTS {
473            state.update(|s| {
474                s.ids
475                    .inv_slots
476                    .resize(2 * MAX_TRADE_SLOTS, &mut ui.widget_id_generator());
477            });
478        }
479
480        for i in 0..MAX_TRADE_SLOTS {
481            let x = i % 4;
482            let y = i / 4;
483
484            let slot = tradeslots.get(i).cloned().unwrap_or(TradeSlot {
485                index: i,
486                quantity: 0,
487                invslot: None,
488                ours,
489                entity,
490            });
491            // Slot
492            let slot_widget = slot_maker
493                .fabricate(slot, [40.0; 2])
494                .top_left_with_margins_on(
495                    state.ids.inv_alignment[who],
496                    0.0 + y as f64 * (40.0),
497                    0.0 + x as f64 * (40.0),
498                );
499            let slot_id = state.ids.inv_slots[i + who * MAX_TRADE_SLOTS];
500            if let Some(Some(item)) = slot.invslot.and_then(|slotid| inventory.slot(slotid)) {
501                let quality_col_img = match item.quality() {
502                    Quality::Low => self.imgs.inv_slot_grey,
503                    Quality::Common => self.imgs.inv_slot_common,
504                    Quality::Moderate => self.imgs.inv_slot_green,
505                    Quality::High => self.imgs.inv_slot_blue,
506                    Quality::Epic => self.imgs.inv_slot_purple,
507                    Quality::Legendary => self.imgs.inv_slot_gold,
508                    Quality::Artifact => self.imgs.inv_slot_orange,
509                    _ => self.imgs.inv_slot_red,
510                };
511
512                slot_widget
513                    .filled_slot(quality_col_img)
514                    .with_item_tooltip(
515                        self.item_tooltip_manager,
516                        core::iter::once(item as &dyn ItemDesc),
517                        prices,
518                        &item_tooltip,
519                    )
520                    .set(slot_id, ui);
521            } else {
522                slot_widget.set(slot_id, ui);
523            }
524        }
525        event
526    }
527
528    fn phase2_itemwidget(
529        &mut self,
530        state: &mut ConrodState<'_, State>,
531        ui: &mut UiCell<'_>,
532        inventory: &Inventory,
533        who: usize,
534        ours: bool,
535        entity: EcsEntity,
536        tradeslots: &[TradeSlot],
537    ) {
538        if state.ids.inv_textslots.len() < 2 * MAX_TRADE_SLOTS {
539            state.update(|s| {
540                s.ids
541                    .inv_textslots
542                    .resize(2 * MAX_TRADE_SLOTS, &mut ui.widget_id_generator());
543            });
544        }
545        let max_width = 170.0;
546        let mut total_text_height = 0.0;
547        let mut total_quantity = 0;
548        for i in 0..MAX_TRADE_SLOTS {
549            let slot = tradeslots.get(i).cloned().unwrap_or(TradeSlot {
550                index: i,
551                quantity: 0,
552                invslot: None,
553                ours,
554                entity,
555            });
556            total_quantity += slot.quantity;
557            let itemname = slot
558                .invslot
559                .and_then(|i| inventory.get(i))
560                .map(|i| {
561                    let (name, _) = util::item_text(&i, self.localized_strings, self.item_i18n);
562
563                    Cow::Owned(name)
564                })
565                .unwrap_or(Cow::Borrowed(""));
566            let is_present = slot.quantity > 0 && slot.invslot.is_some();
567            Text::new(&format!("{}x {}", slot.quantity, &itemname))
568                .top_left_with_margins_on(
569                    state.ids.inv_alignment[who],
570                    15.0 + i as f64 * 20.0 + total_text_height,
571                    0.0,
572                )
573                .font_id(self.fonts.cyri.conrod_id)
574                .font_size(self.fonts.cyri.scale(20))
575                .wrap_by_word()
576                .w(max_width)
577                .color(Color::Rgba(
578                    1.0,
579                    1.0,
580                    1.0,
581                    if is_present { 1.0 } else { 0.0 },
582                ))
583                .set(state.ids.inv_textslots[i + who * MAX_TRADE_SLOTS], ui);
584            let label_height = match ui
585                .widget_graph()
586                .widget(state.ids.inv_textslots[i + who * MAX_TRADE_SLOTS])
587                .map(|widget| widget.rect)
588            {
589                Some(label_rect) => label_rect.h(),
590                None => 10.0,
591            };
592            total_text_height += label_height;
593        }
594        if total_quantity == 0 {
595            Text::new("Nothing!")
596                .top_left_with_margins_on(state.ids.inv_alignment[who], 10.0, 0.0)
597                .font_id(self.fonts.cyri.conrod_id)
598                .font_size(self.fonts.cyri.scale(20))
599                .color(Color::Rgba(
600                    1.0,
601                    0.25 + 0.25 * (4.0 * self.pulse).sin(),
602                    0.0,
603                    1.0,
604                ))
605                .set(state.ids.inv_textslots[who * MAX_TRADE_SLOTS], ui);
606
607            if !ours {
608                self.needs_thirdconfirm = true;
609            }
610        }
611    }
612
613    fn accept_decline_buttons(
614        &mut self,
615        state: &mut ConrodState<'_, State>,
616        ui: &mut UiCell<'_>,
617        trade: &'a PendingTrade,
618    ) -> Option<TradeEvent> {
619        let mut event = None;
620        let (hover_img, press_img, accept_button_luminance) = if trade.is_empty_trade() {
621            //Darken the accept button if the trade is empty.
622            (
623                self.imgs.button,
624                self.imgs.button,
625                Color::Rgba(0.6, 0.6, 0.6, 1.0),
626            )
627        } else {
628            (
629                self.imgs.button_hover,
630                self.imgs.button_press,
631                Color::Rgba(1.0, 1.0, 1.0, 1.0),
632            )
633        };
634        if Button::image(self.imgs.button)
635            .w_h(31.0 * 5.0, 12.0 * 2.0)
636            .hover_image(hover_img)
637            .press_image(press_img)
638            .image_color(accept_button_luminance)
639            .bottom_left_with_margins_on(state.ids.bg, 90.0, 47.0)
640            .label(&self.localized_strings.get_msg("hud-trade-accept"))
641            .label_font_size(self.fonts.cyri.scale(14))
642            .label_color(TEXT_COLOR)
643            .label_font_id(self.fonts.cyri.conrod_id)
644            .label_y(Relative::Scalar(2.0))
645            .set(state.ids.accept_button, ui)
646            .was_clicked()
647        {
648            if matches!(trade.phase, TradePhase::Review) && self.needs_thirdconfirm {
649                event = Some(TradeEvent::ShowPrompt(PromptDialogSettings::new(
650                    self.localized_strings
651                        .get_msg("hud-confirm-trade-for-nothing")
652                        .to_string(),
653                    HudEvent::TradeAction(TradeAction::Accept(trade.phase())),
654                    None,
655                )));
656            } else {
657                event = Some(TradeEvent::TradeAction(TradeAction::Accept(trade.phase())));
658            }
659        }
660
661        if Button::image(self.imgs.button)
662            .w_h(31.0 * 5.0, 12.0 * 2.0)
663            .hover_image(self.imgs.button_hover)
664            .press_image(self.imgs.button_press)
665            .right_from(state.ids.accept_button, 20.0)
666            .label(&self.localized_strings.get_msg("hud-trade-decline"))
667            .label_font_size(self.fonts.cyri.scale(14))
668            .label_color(TEXT_COLOR)
669            .label_font_id(self.fonts.cyri.conrod_id)
670            .label_y(Relative::Scalar(2.0))
671            .set(state.ids.decline_button, ui)
672            .was_clicked()
673        {
674            event = Some(TradeEvent::TradeAction(TradeAction::Decline));
675        }
676        event
677    }
678
679    fn input_item_amount(
680        &mut self,
681        state: &mut ConrodState<'_, State>,
682        ui: &mut UiCell<'_>,
683        trade: &'a PendingTrade,
684    ) -> Option<TradeEvent> {
685        let mut event = None;
686        let selected = self.slot_manager.selected().and_then(|s| match s {
687            SlotKind::Trade(t_s) => t_s.invslot.and_then(|slot| {
688                let who: usize = trade.offers[0].get(&slot).and(Some(0)).unwrap_or(1);
689                self.client
690                    .inventories()
691                    .get(t_s.entity)?
692                    .get(slot)
693                    .map(|item| (t_s.ours, slot, item.amount(), who))
694            }),
695            _ => None,
696        });
697        Rectangle::fill([132.0, 20.0])
698            .bottom_right_with_margins_on(state.ids.bg_frame, 16.0, 32.0)
699            .hsla(
700                0.0,
701                0.0,
702                0.0,
703                if self.show.trade_amount_input_key.is_some() {
704                    0.75
705                } else {
706                    0.35
707                },
708            )
709            .set(state.ids.amount_bg, ui);
710        if let Some((ours, slot, inv, who)) = selected {
711            self.show.trade_amount_input_key = None;
712            // Text for the amount of items offered.
713            let input = trade.offers[who]
714                .get(&slot)
715                .map(|u| format!("{}", u))
716                .unwrap_or_else(String::new);
717            Text::new(&input)
718                .top_left_with_margins_on(state.ids.amount_bg, 0.0, 22.0)
719                .font_id(self.fonts.cyri.conrod_id)
720                .font_size(self.fonts.cyri.scale(14))
721                .color(TEXT_COLOR.alpha(0.7))
722                .set(state.ids.amount_open_label, ui);
723            if Button::image(self.imgs.edit_btn)
724                .hover_image(self.imgs.edit_btn_hover)
725                .press_image(self.imgs.edit_btn_press)
726                .mid_left_with_margin_on(state.ids.amount_bg, 2.0)
727                .w_h(16.0, 16.0)
728                .set(state.ids.amount_open_btn, ui)
729                .was_clicked()
730            {
731                event = Some(HudUpdate::Focus(state.ids.amount_input));
732                self.slot_manager.idle();
733                self.show.trade_amount_input_key =
734                    Some(TradeAmountInput::new(slot, input, inv, ours, who));
735            }
736            Rectangle::fill_with([132.0, 20.0], color::TRANSPARENT)
737                .top_left_of(state.ids.amount_bg)
738                .graphics_for(state.ids.amount_open_btn)
739                .set(state.ids.amount_open_ovlay, ui);
740        } else if let Some(key) = &mut self.show.trade_amount_input_key {
741            if !Hud::is_captured::<TextEdit>(ui) && key.input_painted {
742                // If the text edit is not captured submit the amount.
743                event = Some(HudUpdate::Submit);
744            }
745
746            if Button::image(self.imgs.close_btn)
747                .hover_image(self.imgs.close_btn_hover)
748                .press_image(self.imgs.close_btn_press)
749                .mid_left_with_margin_on(state.ids.amount_bg, 2.0)
750                .w_h(16.0, 16.0)
751                .set(state.ids.amount_btn, ui)
752                .was_clicked()
753            {
754                event = Some(HudUpdate::Submit);
755            }
756            // Input for making TradeAction requests
757            key.input_painted = true;
758            let text_color = key.err.as_ref().and(Some(color::RED)).unwrap_or(TEXT_COLOR);
759            if let Some(new_input) = TextEdit::new(&key.input)
760                .mid_left_with_margin_on(state.ids.amount_bg, 22.0)
761                .w_h(138.0, 20.0)
762                .font_id(self.fonts.cyri.conrod_id)
763                .font_size(self.fonts.cyri.scale(14))
764                .color(text_color)
765                .set(state.ids.amount_input, ui)
766            {
767                if new_input != key.input {
768                    new_input.trim().clone_into(&mut key.input);
769                    if !key.input.is_empty() {
770                        // trade amount can change with (shift||ctrl)-click
771                        let amount = *trade.offers[key.who].get(&key.slot).unwrap_or(&0);
772                        match key.input.parse::<i32>() {
773                            Ok(new_amount) => {
774                                key.input = format!("{}", new_amount);
775                                if new_amount > -1 && new_amount <= key.inv as i32 {
776                                    key.err = None;
777                                    let delta = new_amount - amount as i32;
778                                    key.submit_action =
779                                        TradeAction::item(key.slot, delta, key.ours);
780                                } else {
781                                    key.err = Some("out of range".to_owned());
782                                    key.submit_action = None;
783                                }
784                            },
785                            Err(_) => {
786                                key.err = Some("bad quantity".to_owned());
787                                key.submit_action = None;
788                            },
789                        }
790                    } else {
791                        key.submit_action = None;
792                    }
793                }
794            }
795        } else {
796            // placeholder text when no trade slot is selected
797            Text::new(&self.localized_strings.get_msg("hud-trade-amount_input"))
798                .middle_of(state.ids.amount_bg)
799                .font_id(self.fonts.cyri.conrod_id)
800                .font_size(self.fonts.cyri.scale(14))
801                .color(TEXT_GRAY_COLOR.alpha(0.25))
802                .set(state.ids.amount_notice, ui);
803        }
804        event.map(TradeEvent::HudUpdate)
805    }
806
807    fn close_button(
808        &mut self,
809        state: &mut ConrodState<'_, State>,
810        ui: &mut UiCell<'_>,
811    ) -> Option<TradeEvent> {
812        if Button::image(self.imgs.close_btn)
813            .w_h(24.0, 25.0)
814            .hover_image(self.imgs.close_btn_hover)
815            .press_image(self.imgs.close_btn_press)
816            .top_right_with_margins_on(state.ids.bg, 0.0, 0.0)
817            .set(state.ids.trade_close, ui)
818            .was_clicked()
819        {
820            Some(TradeEvent::TradeAction(TradeAction::Decline))
821        } else {
822            None
823        }
824    }
825}
826
827impl Widget for Trade<'_> {
828    type Event = Option<TradeEvent>;
829    type State = State;
830    type Style = ();
831
832    fn init_state(&self, mut id_gen: widget::id::Generator) -> Self::State {
833        State {
834            bg_ids: BackgroundIds {
835                bg: id_gen.next(),
836                bg_frame: id_gen.next(),
837            },
838            ids: Ids::new(id_gen),
839        }
840    }
841
842    fn style(&self) -> Self::Style {}
843
844    fn update(mut self, args: widget::UpdateArgs<Self>) -> Self::Event {
845        common_base::prof_span!("Trade::update");
846        let widget::UpdateArgs { state, ui, .. } = args;
847
848        let mut event = None;
849        let (trade, prices) = match self.client.pending_trade() {
850            Some((_, trade, prices)) => (trade, prices),
851            None => return Some(TradeEvent::TradeAction(TradeAction::Decline)),
852        };
853
854        if state.ids.inv_alignment.len() < 2 {
855            state.update(|s| {
856                s.ids.inv_alignment.resize(2, &mut ui.widget_id_generator());
857            });
858        }
859        if state.ids.offer_headers.len() < 2 {
860            state.update(|s| {
861                s.ids.offer_headers.resize(2, &mut ui.widget_id_generator());
862            });
863        }
864        if state.ids.accept_indicators.len() < 2 {
865            state.update(|s| {
866                s.ids
867                    .accept_indicators
868                    .resize(2, &mut ui.widget_id_generator());
869            });
870        }
871
872        self.background(state, ui);
873        self.title(state, ui);
874        self.phase_indicator(state, ui, trade);
875
876        event = self.item_pane(state, ui, trade, prices, false).or(event);
877        event = self.item_pane(state, ui, trade, prices, true).or(event);
878        event = self.accept_decline_buttons(state, ui, trade).or(event);
879        event = self.close_button(state, ui).or(event);
880        self.input_item_amount(state, ui, trade).or(event)
881    }
882}