UI: initialize drag-lock x/y axis from region type
[blender.git] / source / blender / editors / interface / interface_handlers.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_handlers.c
27  *  \ingroup edinterface
28  */
29
30 #include <float.h>
31 #include <limits.h>
32 #include <math.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <assert.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_brush_types.h"
41
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44
45 #include "BLI_math.h"
46 #include "BLI_listbase.h"
47 #include "BLI_linklist.h"
48 #include "BLI_string.h"
49 #include "BLI_string_utf8.h"
50 #include "BLI_string_cursor_utf8.h"
51 #include "BLI_rect.h"
52 #include "BLI_utildefines.h"
53
54 #include "PIL_time.h"
55
56 #include "BKE_colorband.h"
57 #include "BKE_blender_undo.h"
58 #include "BKE_brush.h"
59 #include "BKE_colortools.h"
60 #include "BKE_context.h"
61 #include "BKE_report.h"
62 #include "BKE_screen.h"
63 #include "BKE_tracking.h"
64 #include "BKE_unit.h"
65 #include "BKE_paint.h"
66
67 #include "ED_screen.h"
68 #include "ED_undo.h"
69
70 #include "UI_interface.h"
71 #include "UI_view2d.h"
72
73 #include "BLF_api.h"
74
75 #include "interface_intern.h"
76
77 #include "RNA_access.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81 #include "wm_event_system.h"
82
83 #ifdef WITH_INPUT_IME
84 #  include "wm_window.h"
85 #  include "BLT_translation.h"
86 #  include "BLT_lang.h"
87 #endif
88
89 /* place the mouse at the scaled down location when un-grabbing */
90 #define USE_CONT_MOUSE_CORRECT
91 /* support dragging toggle buttons */
92 #define USE_DRAG_TOGGLE
93
94 /* support dragging multiple number buttons at once */
95 #define USE_DRAG_MULTINUM
96
97 /* allow dragging/editing all other selected items at once */
98 #define USE_ALLSELECT
99
100 /* so we can avoid very small mouse-moves from jumping away from keyboard navigation [#34936] */
101 #define USE_KEYNAV_LIMIT
102
103 /* drag popups by their header */
104 #define USE_DRAG_POPUP
105
106 #define UI_MAX_PASSWORD_STR 128
107
108 /* proto */
109 static int ui_do_but_EXIT(bContext *C, uiBut *but, struct uiHandleButtonData *data, const wmEvent *event);
110 static bool ui_but_find_select_in_enum__cmp(const uiBut *but_a, const uiBut *but_b);
111 static void ui_textedit_string_set(uiBut *but, struct uiHandleButtonData *data, const char *str);
112
113 #ifdef USE_KEYNAV_LIMIT
114 static void ui_mouse_motion_keynav_init(struct uiKeyNavLock *keynav, const wmEvent *event);
115 static bool ui_mouse_motion_keynav_test(struct uiKeyNavLock *keynav, const wmEvent *event);
116 #endif
117
118 /***************** structs and defines ****************/
119
120 #define BUTTON_FLASH_DELAY          0.020
121 #define MENU_SCROLL_INTERVAL        0.1
122 #define PIE_MENU_INTERVAL           0.01
123 #define BUTTON_AUTO_OPEN_THRESH     0.2
124 #define BUTTON_MOUSE_TOWARDS_THRESH 1.0
125 /* pixels to move the cursor to get out of keyboard navigation */
126 #define BUTTON_KEYNAV_PX_LIMIT      8
127
128 #define MENU_TOWARDS_MARGIN 20  /* margin in pixels */
129 #define MENU_TOWARDS_WIGGLE_ROOM 64  /* tolerance in pixels */
130 /* drag-lock distance threshold in pixels */
131 #define BUTTON_DRAGLOCK_THRESH      3
132
133 typedef enum uiButtonActivateType {
134         BUTTON_ACTIVATE_OVER,
135         BUTTON_ACTIVATE,
136         BUTTON_ACTIVATE_APPLY,
137         BUTTON_ACTIVATE_TEXT_EDITING,
138         BUTTON_ACTIVATE_OPEN
139 } uiButtonActivateType;
140
141 typedef enum uiHandleButtonState {
142         BUTTON_STATE_INIT,
143         BUTTON_STATE_HIGHLIGHT,
144         BUTTON_STATE_WAIT_FLASH,
145         BUTTON_STATE_WAIT_RELEASE,
146         BUTTON_STATE_WAIT_KEY_EVENT,
147         BUTTON_STATE_NUM_EDITING,
148         BUTTON_STATE_TEXT_EDITING,
149         BUTTON_STATE_TEXT_SELECTING,
150         BUTTON_STATE_MENU_OPEN,
151         BUTTON_STATE_WAIT_DRAG,
152         BUTTON_STATE_EXIT
153 } uiHandleButtonState;
154
155
156 #ifdef USE_ALLSELECT
157
158 /* Unfortunately there's no good way handle more generally:
159  * (propagate single clicks on layer buttons to other objects) */
160 #define USE_ALLSELECT_LAYER_HACK
161
162 typedef struct uiSelectContextElem {
163         PointerRNA ptr;
164         union {
165                 bool  val_b;
166                 int   val_i;
167                 float val_f;
168         };
169 } uiSelectContextElem;
170
171 typedef struct uiSelectContextStore {
172         uiSelectContextElem *elems;
173         int elems_len;
174         bool do_free;
175         bool is_enabled;
176         /* When set, simply copy values (don't apply difference).
177          * Rules are:
178          * - dragging numbers uses delta.
179          * - typing in values will assign to all. */
180         bool is_copy;
181 } uiSelectContextStore;
182
183 static bool ui_selectcontext_begin(
184         bContext *C, uiBut *but, struct uiSelectContextStore *selctx_data);
185 static void ui_selectcontext_end(
186         uiBut *but, uiSelectContextStore *selctx_data);
187 static void ui_selectcontext_apply(
188         bContext *C, uiBut *but, struct uiSelectContextStore *selctx_data,
189         const double value, const double value_orig);
190
191 #define IS_ALLSELECT_EVENT(event) ((event)->alt != 0)
192
193 /** just show a tinted color so users know its activated */
194 #define UI_BUT_IS_SELECT_CONTEXT UI_BUT_NODE_ACTIVE
195
196 #endif  /* USE_ALLSELECT */
197
198
199 #ifdef USE_DRAG_MULTINUM
200
201 /**
202  * how far to drag before we check for gesture direction (in pixels),
203  * note: half the height of a button is about right... */
204 #define DRAG_MULTINUM_THRESHOLD_DRAG_X (UI_UNIT_Y / 4)
205
206 /**
207  * how far to drag horizontally before we stop checking which buttons the gesture spans (in pixels),
208  * locking down the buttons so we can drag freely without worrying about vertical movement. */
209 #define DRAG_MULTINUM_THRESHOLD_DRAG_Y (UI_UNIT_Y / 4)
210
211 /**
212  * how strict to be when detecting a vertical gesture, [0.5 == sloppy], [0.9 == strict], (unsigned dot-product)
213  * note: we should be quite strict here, since doing a vertical gesture by accident should be avoided,
214  * however with some care a user should be able to do a vertical movement without *missing*. */
215 #define DRAG_MULTINUM_THRESHOLD_VERTICAL (0.75f)
216
217
218 /* a simple version of uiHandleButtonData when accessing multiple buttons */
219 typedef struct uiButMultiState {
220         double origvalue;
221         uiBut *but;
222
223 #ifdef USE_ALLSELECT
224         uiSelectContextStore select_others;
225 #endif
226 } uiButMultiState;
227
228 typedef struct uiHandleButtonMulti {
229         enum {
230                 BUTTON_MULTI_INIT_UNSET = 0,    /* gesture direction unknown, wait until mouse has moved enough... */
231                 BUTTON_MULTI_INIT_SETUP,        /* vertical gesture detected, flag buttons interactively (UI_BUT_DRAG_MULTI) */
232                 BUTTON_MULTI_INIT_ENABLE,       /* flag buttons finished, apply horizontal motion to active and flagged */
233                 BUTTON_MULTI_INIT_DISABLE,      /* vertical gesture _not_ detected, take no further action */
234         } init;
235
236         bool has_mbuts;  /* any buttons flagged UI_BUT_DRAG_MULTI */
237         LinkNode *mbuts;
238         uiButStore *bs_mbuts;
239
240         bool is_proportional;
241
242         /* In some cases we directly apply the changes to multiple buttons, so we don't want to do it twice. */
243         bool skip;
244
245         /* before activating, we need to check gesture direction
246          * accumulate signed cursor movement here so we can tell if this is a vertical motion or not. */
247         float drag_dir[2];
248
249         /* values copied direct from event->x,y
250          * used to detect buttons between the current and initial mouse position */
251         int drag_start[2];
252
253         /* store x location once BUTTON_MULTI_INIT_SETUP is set,
254          * moving outside this sets BUTTON_MULTI_INIT_ENABLE */
255         int drag_lock_x;
256
257 } uiHandleButtonMulti;
258
259 #endif  /* USE_DRAG_MULTINUM */
260
261 typedef struct uiHandleButtonData {
262         wmWindowManager *wm;
263         wmWindow *window;
264         ARegion *region;
265
266         bool interactive;
267
268         /* overall state */
269         uiHandleButtonState state;
270         int retval;
271         /* booleans (could be made into flags) */
272         bool cancel, escapecancel;
273         bool applied, applied_interactive;
274         bool changed_cursor;
275         wmTimer *flashtimer;
276
277         /* edited value */
278         /* use 'ui_textedit_string_set' to assign new strings */
279         char *str;
280         char *origstr;
281         double value, origvalue, startvalue;
282         float vec[3], origvec[3];
283 #if 0  /* UNUSED */
284         int togdual, togonly;
285 #endif
286         ColorBand *coba;
287
288         /* tooltip */
289         unsigned int tooltip_force : 1;
290
291         /* auto open */
292         bool used_mouse;
293         wmTimer *autoopentimer;
294
295         /* auto open (hold) */
296         wmTimer *hold_action_timer;
297
298         /* text selection/editing */
299         /* size of 'str' (including terminator) */
300         int maxlen;
301         /* Button text selection:
302          * extension direction, selextend, inside ui_do_but_TEX */
303         enum {
304                 EXTEND_NONE =     0,
305                 EXTEND_LEFT =     1,
306                 EXTEND_RIGHT =    2,
307         } selextend;
308         float selstartx;
309         /* allow to realloc str/editstr and use 'maxlen' to track alloc size (maxlen + 1) */
310         bool is_str_dynamic;
311
312         /* number editing / dragging */
313         /* coords are Window/uiBlock relative (depends on the button) */
314         int draglastx, draglasty;
315         int dragstartx, dragstarty;
316         int draglastvalue;
317         int dragstartvalue;
318         bool dragchange, draglock;
319         int dragsel;
320         float dragf, dragfstart;
321         CBData *dragcbd;
322
323 #ifdef USE_CONT_MOUSE_CORRECT
324         /* when ungrabbing buttons which are #ui_but_is_cursor_warp(), we may want to position them
325          * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space  */
326         float ungrab_mval[2];
327 #endif
328
329         /* menu open (watch UI_screen_free_active_but) */
330         uiPopupBlockHandle *menu;
331         int menuretval;
332
333         /* search box (watch UI_screen_free_active_but) */
334         ARegion *searchbox;
335 #ifdef USE_KEYNAV_LIMIT
336         struct uiKeyNavLock searchbox_keynav_state;
337 #endif
338
339 #ifdef USE_DRAG_MULTINUM
340         /* Multi-buttons will be updated in unison with the active button. */
341         uiHandleButtonMulti multi_data;
342 #endif
343
344 #ifdef USE_ALLSELECT
345         uiSelectContextStore select_others;
346 #endif
347
348         /* post activate */
349         uiButtonActivateType posttype;
350         uiBut *postbut;
351 } uiHandleButtonData;
352
353 typedef struct uiAfterFunc {
354         struct uiAfterFunc *next, *prev;
355
356         uiButHandleFunc func;
357         void *func_arg1;
358         void *func_arg2;
359
360         uiButHandleNFunc funcN;
361         void *func_argN;
362
363         uiButHandleRenameFunc rename_func;
364         void *rename_arg1;
365         void *rename_orig;
366
367         uiBlockHandleFunc handle_func;
368         void *handle_func_arg;
369         int retval;
370
371         uiMenuHandleFunc butm_func;
372         void *butm_func_arg;
373         int a2;
374
375         wmOperator *popup_op;
376         wmOperatorType *optype;
377         int opcontext;
378         PointerRNA *opptr;
379
380         PointerRNA rnapoin;
381         PropertyRNA *rnaprop;
382
383         bContextStore *context;
384
385         char undostr[BKE_UNDO_STR_MAX];
386 } uiAfterFunc;
387
388
389
390 static bool ui_but_is_interactive(const uiBut *but, const bool labeledit);
391 static bool ui_but_contains_pt(uiBut *but, float mx, float my);
392 static bool ui_but_contains_point_px(ARegion *ar, uiBut *but, int x, int y);
393 static uiBut *ui_but_find_mouse_over_ex(ARegion *ar, const int x, const int y, const bool labeledit);
394 static void button_activate_init(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
395 static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState state);
396 static void button_activate_exit(
397         bContext *C, uiBut *but, uiHandleButtonData *data,
398         const bool mousemove, const bool onfree);
399 static int ui_handler_region_menu(bContext *C, const wmEvent *event, void *userdata);
400 static void ui_handle_button_activate(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
401
402 #ifdef USE_DRAG_MULTINUM
403 static void ui_multibut_restore(bContext *C, uiHandleButtonData *data, uiBlock *block);
404 static uiButMultiState *ui_multibut_lookup(uiHandleButtonData *data, const uiBut *but);
405 #endif
406
407 /* buttons clipboard */
408 static ColorBand but_copypaste_coba = {0};
409 static CurveMapping but_copypaste_curve = {0};
410 static bool but_copypaste_curve_alive = false;
411
412 /* ******************** menu navigation helpers ************** */
413 enum eSnapType {
414         SNAP_OFF = 0,
415         SNAP_ON,
416         SNAP_ON_SMALL,
417 };
418
419 static enum eSnapType ui_event_to_snap(const wmEvent *event)
420 {
421         return (event->ctrl) ? (event->shift) ? SNAP_ON_SMALL : SNAP_ON : SNAP_OFF;
422 }
423
424 static bool ui_event_is_snap(const wmEvent *event)
425 {
426         return (ELEM(event->type, LEFTCTRLKEY, RIGHTCTRLKEY) ||
427                 ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY));
428 }
429
430 static void ui_color_snap_hue(const enum eSnapType snap, float *r_hue)
431 {
432         const float snap_increment = (snap == SNAP_ON_SMALL) ? 24 : 12;
433         BLI_assert(snap != SNAP_OFF);
434         *r_hue = roundf((*r_hue) * snap_increment) / snap_increment;
435 }
436
437 /* assumes event type is MOUSEPAN */
438 void ui_pan_to_scroll(const wmEvent *event, int *type, int *val)
439 {
440         static int lastdy = 0;
441         int dy = event->prevy - event->y;
442
443         /* This event should be originally from event->type,
444          * converting wrong event into wheel is bad, see [#33803] */
445         BLI_assert(*type == MOUSEPAN);
446
447         /* sign differs, reset */
448         if ((dy > 0 && lastdy < 0) || (dy < 0 && lastdy > 0)) {
449                 lastdy = dy;
450         }
451         else {
452                 lastdy += dy;
453
454                 if (ABS(lastdy) > (int)UI_UNIT_Y) {
455                         if (U.uiflag2 & USER_TRACKPAD_NATURAL)
456                                 dy = -dy;
457
458                         *val = KM_PRESS;
459
460                         if (dy > 0)
461                                 *type = WHEELUPMOUSE;
462                         else
463                                 *type = WHEELDOWNMOUSE;
464
465                         lastdy = 0;
466                 }
467         }
468 }
469
470 static uiBut *ui_but_prev(uiBut *but)
471 {
472         while (but->prev) {
473                 but = but->prev;
474                 if (ui_but_is_editable(but)) return but;
475         }
476         return NULL;
477 }
478
479 static uiBut *ui_but_next(uiBut *but)
480 {
481         while (but->next) {
482                 but = but->next;
483                 if (ui_but_is_editable(but)) return but;
484         }
485         return NULL;
486 }
487
488 static uiBut *ui_but_first(uiBlock *block)
489 {
490         uiBut *but;
491
492         but = block->buttons.first;
493         while (but) {
494                 if (ui_but_is_editable(but)) return but;
495                 but = but->next;
496         }
497         return NULL;
498 }
499
500 static uiBut *ui_but_last(uiBlock *block)
501 {
502         uiBut *but;
503
504         but = block->buttons.last;
505         while (but) {
506                 if (ui_but_is_editable(but)) return but;
507                 but = but->prev;
508         }
509         return NULL;
510 }
511
512 static bool ui_but_is_cursor_warp(uiBut *but)
513 {
514         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
515                 if (ELEM(but->type,
516                          UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER, UI_BTYPE_HSVCIRCLE,
517                          UI_BTYPE_TRACK_PREVIEW, UI_BTYPE_HSVCUBE, UI_BTYPE_CURVE))
518                 {
519                         return true;
520                 }
521         }
522
523         return false;
524 }
525
526 /**
527  * Ignore mouse movements within some horizontal pixel threshold before starting to drag
528  */
529 static bool ui_but_dragedit_update_mval(uiHandleButtonData *data, int mx)
530 {
531         if (mx == data->draglastx)
532                 return false;
533
534         if (data->draglock) {
535                 if (ABS(mx - data->dragstartx) <= BUTTON_DRAGLOCK_THRESH) {
536                         return false;
537                 }
538 #ifdef USE_DRAG_MULTINUM
539                 if (ELEM(data->multi_data.init, BUTTON_MULTI_INIT_UNSET, BUTTON_MULTI_INIT_SETUP)) {
540                         return false;
541                 }
542 #endif
543                 data->draglock = false;
544                 data->dragstartx = mx;  /* ignore mouse movement within drag-lock */
545         }
546
547         return true;
548 }
549
550 static float ui_mouse_scale_warp_factor(const bool shift)
551 {
552         return shift ? 0.05f : 1.0f;
553 }
554
555 static void ui_mouse_scale_warp(
556         uiHandleButtonData *data, const float mx, const float my,
557         float *r_mx, float *r_my, const bool shift)
558 {
559         const float fac = ui_mouse_scale_warp_factor(shift);
560
561         /* slow down the mouse, this is fairly picky */
562         *r_mx = (data->dragstartx * (1.0f - fac) + mx * fac);
563         *r_my = (data->dragstarty * (1.0f - fac) + my * fac);
564 }
565
566 /* file selectors are exempt from utf-8 checks */
567 bool ui_but_is_utf8(const uiBut *but)
568 {
569         if (but->rnaprop) {
570                 const int subtype = RNA_property_subtype(but->rnaprop);
571                 return !(ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME, PROP_BYTESTRING));
572         }
573         else {
574                 return !(but->flag & UI_BUT_NO_UTF8);
575         }
576 }
577
578 /* ********************** button apply/revert ************************/
579
580 static ListBase UIAfterFuncs = {NULL, NULL};
581
582 static uiAfterFunc *ui_afterfunc_new(void)
583 {
584         uiAfterFunc *after;
585
586         after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
587
588         BLI_addtail(&UIAfterFuncs, after);
589
590         return after;
591 }
592
593 /**
594  * For executing operators after the button is pressed.
595  * (some non operator buttons need to trigger operators), see: [#37795]
596  *
597  * \note Can only call while handling buttons.
598  */
599 PointerRNA *ui_handle_afterfunc_add_operator(wmOperatorType *ot, int opcontext, bool create_props)
600 {
601         PointerRNA *ptr = NULL;
602         uiAfterFunc *after = ui_afterfunc_new();
603
604         after->optype = ot;
605         after->opcontext = opcontext;
606
607         if (create_props) {
608                 ptr = MEM_callocN(sizeof(PointerRNA), __func__);
609                 WM_operator_properties_create_ptr(ptr, ot);
610                 after->opptr = ptr;
611         }
612
613         return ptr;
614 }
615
616 static void popup_check(bContext *C, wmOperator *op)
617 {
618         if (op && op->type->check) {
619                 op->type->check(C, op);
620         }
621 }
622
623 /**
624  * Check if a #uiAfterFunc is needed for this button.
625  */
626 static bool ui_afterfunc_check(const uiBlock *block, const uiBut *but)
627 {
628         return (but->func || but->funcN || but->rename_func || but->optype || but->rnaprop || block->handle_func ||
629                 (but->type == UI_BTYPE_BUT_MENU && block->butm_func) ||
630                 (block->handle && block->handle->popup_op));
631 }
632
633 static void ui_apply_but_func(bContext *C, uiBut *but)
634 {
635         uiAfterFunc *after;
636         uiBlock *block = but->block;
637
638         /* these functions are postponed and only executed after all other
639          * handling is done, i.e. menus are closed, in order to avoid conflicts
640          * with these functions removing the buttons we are working with */
641
642         if (ui_afterfunc_check(block, but)) {
643                 after = ui_afterfunc_new();
644
645                 if (but->func && ELEM(but, but->func_arg1, but->func_arg2)) {
646                         /* exception, this will crash due to removed button otherwise */
647                         but->func(C, but->func_arg1, but->func_arg2);
648                 }
649                 else
650                         after->func = but->func;
651
652                 after->func_arg1 = but->func_arg1;
653                 after->func_arg2 = but->func_arg2;
654
655                 after->funcN = but->funcN;
656                 after->func_argN = (but->func_argN) ? MEM_dupallocN(but->func_argN) : NULL;
657
658                 after->rename_func = but->rename_func;
659                 after->rename_arg1 = but->rename_arg1;
660                 after->rename_orig = but->rename_orig; /* needs free! */
661
662                 after->handle_func = block->handle_func;
663                 after->handle_func_arg = block->handle_func_arg;
664                 after->retval = but->retval;
665
666                 if (but->type == UI_BTYPE_BUT_MENU) {
667                         after->butm_func = block->butm_func;
668                         after->butm_func_arg = block->butm_func_arg;
669                         after->a2 = but->a2;
670                 }
671
672                 if (block->handle)
673                         after->popup_op = block->handle->popup_op;
674
675                 after->optype = but->optype;
676                 after->opcontext = but->opcontext;
677                 after->opptr = but->opptr;
678
679                 after->rnapoin = but->rnapoin;
680                 after->rnaprop = but->rnaprop;
681
682                 if (but->context)
683                         after->context = CTX_store_copy(but->context);
684
685                 but->optype = NULL;
686                 but->opcontext = 0;
687                 but->opptr = NULL;
688         }
689 }
690
691 /* typically call ui_apply_but_undo(), ui_apply_but_autokey() */
692 static void ui_apply_but_undo(uiBut *but)
693 {
694         uiAfterFunc *after;
695
696         if (but->flag & UI_BUT_UNDO) {
697                 const char *str = NULL;
698
699                 /* define which string to use for undo */
700                 if (but->type == UI_BTYPE_MENU) str = but->drawstr;
701                 else if (but->drawstr[0]) str = but->drawstr;
702                 else str = but->tip;
703
704                 /* fallback, else we don't get an undo! */
705                 if (str == NULL || str[0] == '\0') {
706                         str = "Unknown Action";
707                 }
708
709                 /* delayed, after all other funcs run, popups are closed, etc */
710                 after = ui_afterfunc_new();
711                 BLI_strncpy(after->undostr, str, sizeof(after->undostr));
712         }
713 }
714
715 static void ui_apply_but_autokey(bContext *C, uiBut *but)
716 {
717         Scene *scene = CTX_data_scene(C);
718
719         /* try autokey */
720         ui_but_anim_autokey(C, but, scene, scene->r.cfra);
721
722         /* make a little report about what we've done! */
723         if (but->rnaprop) {
724                 char *buf;
725
726                 if (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD) {
727                         return;
728                 }
729
730                 buf = WM_prop_pystring_assign(C, &but->rnapoin, but->rnaprop, but->rnaindex);
731                 if (buf) {
732                         BKE_report(CTX_wm_reports(C), RPT_PROPERTY, buf);
733                         MEM_freeN(buf);
734
735                         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
736                 }
737         }
738 }
739
740 static void ui_apply_but_funcs_after(bContext *C)
741 {
742         uiAfterFunc *afterf, after;
743         PointerRNA opptr;
744         ListBase funcs;
745
746         /* copy to avoid recursive calls */
747         funcs = UIAfterFuncs;
748         BLI_listbase_clear(&UIAfterFuncs);
749
750         for (afterf = funcs.first; afterf; afterf = after.next) {
751                 after = *afterf; /* copy to avoid memleak on exit() */
752                 BLI_freelinkN(&funcs, afterf);
753
754                 if (after.context)
755                         CTX_store_set(C, after.context);
756
757                 if (after.popup_op)
758                         popup_check(C, after.popup_op);
759
760                 if (after.opptr) {
761                         /* free in advance to avoid leak on exit */
762                         opptr = *after.opptr;
763                         MEM_freeN(after.opptr);
764                 }
765
766                 if (after.optype)
767                         WM_operator_name_call_ptr(C, after.optype, after.opcontext, (after.opptr) ? &opptr : NULL);
768
769                 if (after.opptr)
770                         WM_operator_properties_free(&opptr);
771
772                 if (after.rnapoin.data)
773                         RNA_property_update(C, &after.rnapoin, after.rnaprop);
774
775                 if (after.context) {
776                         CTX_store_set(C, NULL);
777                         CTX_store_free(after.context);
778                 }
779
780                 if (after.func)
781                         after.func(C, after.func_arg1, after.func_arg2);
782                 if (after.funcN)
783                         after.funcN(C, after.func_argN, after.func_arg2);
784                 if (after.func_argN)
785                         MEM_freeN(after.func_argN);
786
787                 if (after.handle_func)
788                         after.handle_func(C, after.handle_func_arg, after.retval);
789                 if (after.butm_func)
790                         after.butm_func(C, after.butm_func_arg, after.a2);
791
792                 if (after.rename_func)
793                         after.rename_func(C, after.rename_arg1, after.rename_orig);
794                 if (after.rename_orig)
795                         MEM_freeN(after.rename_orig);
796
797                 if (after.undostr[0])
798                         ED_undo_push(C, after.undostr);
799         }
800 }
801
802 static void ui_apply_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data)
803 {
804         ui_apply_but_func(C, but);
805
806         data->retval = but->retval;
807         data->applied = true;
808 }
809
810 static void ui_apply_but_BUTM(bContext *C, uiBut *but, uiHandleButtonData *data)
811 {
812         ui_but_value_set(but, but->hardmin);
813         ui_apply_but_func(C, but);
814
815         data->retval = but->retval;
816         data->applied = true;
817 }
818
819 static void ui_apply_but_BLOCK(bContext *C, uiBut *but, uiHandleButtonData *data)
820 {
821         if (but->type == UI_BTYPE_MENU)
822                 ui_but_value_set(but, data->value);
823
824         ui_but_update_edited(but);
825         ui_apply_but_func(C, but);
826         data->retval = but->retval;
827         data->applied = true;
828 }
829
830 static void ui_apply_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data)
831 {
832         double value;
833         int w, lvalue, push;
834
835         value = ui_but_value_get(but);
836         lvalue = (int)value;
837
838         if (but->bit) {
839                 w = UI_BITBUT_TEST(lvalue, but->bitnr);
840                 if (w) lvalue = UI_BITBUT_CLR(lvalue, but->bitnr);
841                 else   lvalue = UI_BITBUT_SET(lvalue, but->bitnr);
842
843                 ui_but_value_set(but, (double)lvalue);
844                 if (but->type == UI_BTYPE_ICON_TOGGLE || but->type == UI_BTYPE_ICON_TOGGLE_N) {
845                         ui_but_update_edited(but);
846                 }
847         }
848         else {
849
850                 if (value == 0.0) push = 1;
851                 else push = 0;
852
853                 if (ELEM(but->type, UI_BTYPE_TOGGLE_N, UI_BTYPE_ICON_TOGGLE_N, UI_BTYPE_CHECKBOX_N)) push = !push;
854                 ui_but_value_set(but, (double)push);
855                 if (but->type == UI_BTYPE_ICON_TOGGLE || but->type == UI_BTYPE_ICON_TOGGLE_N) {
856                         ui_but_update_edited(but);
857                 }
858         }
859
860         ui_apply_but_func(C, but);
861
862         data->retval = but->retval;
863         data->applied = true;
864 }
865
866 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
867 {
868         uiBut *bt;
869
870         ui_but_value_set(but, but->hardmax);
871
872         ui_apply_but_func(C, but);
873
874         /* states of other row buttons */
875         for (bt = block->buttons.first; bt; bt = bt->next) {
876                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, UI_BTYPE_ROW, UI_BTYPE_LISTROW)) {
877                         ui_but_update_edited(bt);
878                 }
879         }
880
881         data->retval = but->retval;
882         data->applied = true;
883 }
884
885 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
886 {
887         if (!data->str)
888                 return;
889
890         ui_but_string_set(C, but, data->str);
891         ui_but_update_edited(but);
892
893         /* give butfunc a copy of the original text too.
894          * feature used for bone renaming, channels, etc.
895          * afterfunc frees rename_orig */
896         if (data->origstr && (but->flag & UI_BUT_TEXTEDIT_UPDATE)) {
897                 /* In this case, we need to keep origstr available, to restore real org string in case we cancel after
898                  * having typed something already. */
899                 but->rename_orig = BLI_strdup(data->origstr);
900         }
901         /* only if there are afterfuncs, otherwise 'renam_orig' isn't freed */
902         else if (ui_afterfunc_check(but->block, but)) {
903                 but->rename_orig = data->origstr;
904                 data->origstr = NULL;
905         }
906         ui_apply_but_func(C, but);
907
908         data->retval = but->retval;
909         data->applied = true;
910 }
911
912 static void ui_apply_but_TAB(bContext *C, uiBut *but, uiHandleButtonData *data)
913 {
914         if (data->str) {
915                 ui_but_string_set(C, but, data->str);
916                 ui_but_update_edited(but);
917         }
918         else {
919                 ui_but_value_set(but, but->hardmax);
920                 ui_apply_but_func(C, but);
921         }
922
923         data->retval = but->retval;
924         data->applied = true;
925 }
926
927 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
928 {
929         if (data->str) {
930                 if (ui_but_string_set(C, but, data->str)) {
931                         data->value = ui_but_value_get(but);
932                 }
933                 else {
934                         data->cancel = true;
935                         return;
936                 }
937         }
938         else {
939                 ui_but_value_set(but, data->value);
940         }
941
942         ui_but_update_edited(but);
943         ui_apply_but_func(C, but);
944
945         data->retval = but->retval;
946         data->applied = true;
947 }
948
949 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
950 {
951         ui_but_v3_set(but, data->vec);
952         ui_but_update_edited(but);
953         ui_apply_but_func(C, but);
954
955         data->retval = but->retval;
956         data->applied = true;
957 }
958
959 static void ui_apply_but_COLORBAND(bContext *C, uiBut *but, uiHandleButtonData *data)
960 {
961         ui_apply_but_func(C, but);
962         data->retval = but->retval;
963         data->applied = true;
964 }
965
966 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
967 {
968         ui_apply_but_func(C, but);
969         data->retval = but->retval;
970         data->applied = true;
971 }
972
973 /* ****************** drag drop code *********************** */
974
975
976 #ifdef USE_DRAG_MULTINUM
977
978 /* small multi-but api */
979 static void ui_multibut_add(uiHandleButtonData *data, uiBut *but)
980 {
981         uiButMultiState *mbut_state;
982
983         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
984         BLI_assert(data->multi_data.has_mbuts);
985
986
987         mbut_state = MEM_callocN(sizeof(*mbut_state), __func__);
988         mbut_state->but = but;
989         mbut_state->origvalue = ui_but_value_get(but);
990
991         BLI_linklist_prepend(&data->multi_data.mbuts, mbut_state);
992
993         UI_butstore_register(data->multi_data.bs_mbuts, &mbut_state->but);
994 }
995
996 static uiButMultiState *ui_multibut_lookup(uiHandleButtonData *data, const uiBut *but)
997 {
998         LinkNode *l;
999
1000         for (l = data->multi_data.mbuts; l; l = l->next) {
1001                 uiButMultiState *mbut_state;
1002
1003                 mbut_state = l->link;
1004
1005                 if (mbut_state->but == but) {
1006                         return mbut_state;
1007                 }
1008         }
1009
1010         return NULL;
1011 }
1012
1013 static void ui_multibut_restore(bContext *C, uiHandleButtonData *data, uiBlock *block)
1014 {
1015         uiBut *but;
1016
1017         for (but = block->buttons.first; but; but = but->next) {
1018                 if (but->flag & UI_BUT_DRAG_MULTI) {
1019                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
1020                         if (mbut_state) {
1021                                 ui_but_value_set(but, mbut_state->origvalue);
1022
1023 #ifdef USE_ALLSELECT
1024                                 if (mbut_state->select_others.elems_len > 0) {
1025                                         ui_selectcontext_apply(
1026                                                 C, but, &mbut_state->select_others,
1027                                                 mbut_state->origvalue, mbut_state->origvalue);
1028                                 }
1029 #else
1030                                 UNUSED_VARS(C);
1031 #endif
1032                         }
1033                 }
1034         }
1035 }
1036
1037 static void ui_multibut_free(uiHandleButtonData *data, uiBlock *block)
1038 {
1039 #ifdef USE_ALLSELECT
1040         if (data->multi_data.mbuts) {
1041                 LinkNode *list = data->multi_data.mbuts;
1042                 while (list) {
1043                         LinkNode *next = list->next;
1044                         uiButMultiState *mbut_state = list->link;
1045
1046                         if (mbut_state->select_others.elems) {
1047                                 MEM_freeN(mbut_state->select_others.elems);
1048                         }
1049
1050                         MEM_freeN(list->link);
1051                         MEM_freeN(list);
1052                         list = next;
1053                 }
1054         }
1055 #else
1056         BLI_linklist_freeN(data->multi_data.mbuts);
1057 #endif
1058
1059         data->multi_data.mbuts = NULL;
1060
1061         if (data->multi_data.bs_mbuts) {
1062                 UI_butstore_free(block, data->multi_data.bs_mbuts);
1063                 data->multi_data.bs_mbuts = NULL;
1064         }
1065 }
1066
1067 static bool ui_multibut_states_tag(
1068         uiBut *but_active,
1069         uiHandleButtonData *data, const wmEvent *event)
1070 {
1071         uiBut *but;
1072         float seg[2][2];
1073         bool changed = false;
1074
1075         seg[0][0] = data->multi_data.drag_start[0];
1076         seg[0][1] = data->multi_data.drag_start[1];
1077
1078         seg[1][0] = event->x;
1079         seg[1][1] = event->y;
1080
1081         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
1082
1083         ui_window_to_block_fl(data->region, but_active->block, &seg[0][0], &seg[0][1]);
1084         ui_window_to_block_fl(data->region, but_active->block, &seg[1][0], &seg[1][1]);
1085
1086         data->multi_data.has_mbuts = false;
1087
1088         /* follow ui_but_find_mouse_over_ex logic */
1089         for (but = but_active->block->buttons.first; but; but = but->next) {
1090                 bool drag_prev = false;
1091                 bool drag_curr = false;
1092
1093                 /* re-set each time */
1094                 if (but->flag & UI_BUT_DRAG_MULTI) {
1095                         but->flag &= ~UI_BUT_DRAG_MULTI;
1096                         drag_prev = true;
1097                 }
1098
1099                 if (ui_but_is_interactive(but, false)) {
1100
1101                         /* drag checks */
1102                         if (but_active != but) {
1103                                 if (ui_but_is_compatible(but_active, but)) {
1104
1105                                         BLI_assert(but->active == NULL);
1106
1107                                         /* finally check for overlap */
1108                                         if (BLI_rctf_isect_segment(&but->rect, seg[0], seg[1])) {
1109
1110                                                 but->flag |= UI_BUT_DRAG_MULTI;
1111                                                 data->multi_data.has_mbuts = true;
1112                                                 drag_curr = true;
1113                                         }
1114                                 }
1115                         }
1116                 }
1117
1118                 changed |= (drag_prev != drag_curr);
1119         }
1120
1121         return changed;
1122 }
1123
1124 static void ui_multibut_states_create(uiBut *but_active, uiHandleButtonData *data)
1125 {
1126         uiBut *but;
1127
1128         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
1129         BLI_assert(data->multi_data.has_mbuts);
1130
1131         data->multi_data.bs_mbuts = UI_butstore_create(but_active->block);
1132
1133         for (but = but_active->block->buttons.first; but; but = but->next) {
1134                 if (but->flag & UI_BUT_DRAG_MULTI) {
1135                         ui_multibut_add(data, but);
1136                 }
1137         }
1138
1139         /* edit buttons proportionally to eachother
1140          * note: if we mix buttons which are proportional and others which are not,
1141          * this may work a bit strangely */
1142         if (but_active->rnaprop) {
1143                 if ((data->origvalue != 0.0) && (RNA_property_flag(but_active->rnaprop) & PROP_PROPORTIONAL)) {
1144                         data->multi_data.is_proportional = true;
1145                 }
1146         }
1147 }
1148
1149 static void ui_multibut_states_apply(bContext *C, uiHandleButtonData *data, uiBlock *block)
1150 {
1151         ARegion *ar = data->region;
1152         const double value_delta = data->value - data->origvalue;
1153         const double value_scale = data->multi_data.is_proportional ? (data->value / data->origvalue) : 0.0;
1154         uiBut *but;
1155
1156         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_ENABLE);
1157         BLI_assert(data->multi_data.skip == false);
1158
1159         for (but = block->buttons.first; but; but = but->next) {
1160                 if (but->flag & UI_BUT_DRAG_MULTI) {
1161                         /* mbut_states for delta */
1162                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
1163
1164                         if (mbut_state) {
1165                                 void *active_back;
1166
1167                                 ui_but_execute_begin(C, ar, but, &active_back);
1168
1169 #ifdef USE_ALLSELECT
1170                                 if (data->select_others.is_enabled) {
1171                                         /* init once! */
1172                                         if (mbut_state->select_others.elems_len == 0) {
1173                                                 ui_selectcontext_begin(C, but, &mbut_state->select_others);
1174                                         }
1175                                         if (mbut_state->select_others.elems_len == 0) {
1176                                                 mbut_state->select_others.elems_len = -1;
1177                                         }
1178                                 }
1179
1180                                 /* needed so we apply the right deltas */
1181                                 but->active->origvalue = mbut_state->origvalue;
1182                                 but->active->select_others = mbut_state->select_others;
1183                                 but->active->select_others.do_free = false;
1184 #endif
1185
1186                                 BLI_assert(active_back == NULL);
1187                                 /* no need to check 'data->state' here */
1188                                 if (data->str) {
1189                                         /* entering text (set all) */
1190                                         but->active->value = data->value;
1191                                         ui_but_string_set(C, but, data->str);
1192                                 }
1193                                 else {
1194                                         /* dragging (use delta) */
1195                                         if (data->multi_data.is_proportional) {
1196                                                 but->active->value = mbut_state->origvalue * value_scale;
1197                                         }
1198                                         else {
1199                                                 but->active->value = mbut_state->origvalue + value_delta;
1200                                         }
1201
1202                                         /* clamp based on soft limits, see: T40154 */
1203                                         CLAMP(but->active->value, (double)but->softmin, (double)but->softmax);
1204                                 }
1205                                 ui_but_execute_end(C, ar, but, active_back);
1206                         }
1207                         else {
1208                                 /* highly unlikely */
1209                                 printf("%s: cant find button\n", __func__);
1210                         }
1211                         /* end */
1212
1213                 }
1214         }
1215 }
1216
1217 #endif  /* USE_DRAG_MULTINUM */
1218
1219
1220 #ifdef USE_DRAG_TOGGLE
1221
1222 /* Helpers that wrap boolean functions, to support different kinds of buttons. */
1223
1224 static bool ui_drag_toggle_but_is_supported(const uiBut *but)
1225 {
1226         if (ui_but_is_bool(but)) {
1227                 return true;
1228         }
1229         else if (UI_but_is_decorator(but)) {
1230                 return ELEM(but->icon, ICON_DECORATE, ICON_DECORATE_KEYFRAME, ICON_DECORATE_ANIMATE, ICON_DECORATE_OVERRIDE);
1231         }
1232         else {
1233                 return false;
1234         }
1235 }
1236
1237 static bool ui_drag_toggle_but_is_pushed(uiBut *but)
1238 {
1239         if (ui_but_is_bool(but)) {
1240                 return ui_but_is_pushed(but);
1241         }
1242         else if (UI_but_is_decorator(but)) {
1243                 return (but->icon == ICON_DECORATE_KEYFRAME);
1244         }
1245         else {
1246                 return false;
1247         }
1248 }
1249
1250 typedef struct uiDragToggleHandle {
1251         /* init */
1252         bool is_set;
1253         float but_cent_start[2];
1254
1255         bool is_xy_lock_init;
1256         bool    xy_lock[2];
1257
1258         int  xy_init[2];
1259         int  xy_last[2];
1260 } uiDragToggleHandle;
1261
1262 static bool ui_drag_toggle_set_xy_xy(
1263         bContext *C, ARegion *ar, const bool is_set,
1264         const int xy_src[2], const int xy_dst[2])
1265 {
1266         /* popups such as layers won't re-evaluate on redraw */
1267         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
1268         bool changed = false;
1269         uiBlock *block;
1270
1271         for (block = ar->uiblocks.first; block; block = block->next) {
1272                 uiBut *but;
1273
1274                 float xy_a_block[2] = {UNPACK2(xy_src)};
1275                 float xy_b_block[2] = {UNPACK2(xy_dst)};
1276
1277                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
1278                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
1279
1280                 for (but = block->buttons.first; but; but = but->next) {
1281                         /* Note: ctrl is always true here because (at least for now) we always want to consider text control
1282                          *       in this case, even when not embossed. */
1283                         if (ui_but_is_interactive(but, true)) {
1284                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
1285
1286                                         /* execute the button */
1287                                         if (ui_drag_toggle_but_is_supported(but)) {
1288                                                 /* is it pressed? */
1289                                                 bool is_set_but = ui_drag_toggle_but_is_pushed(but);
1290                                                 if (is_set_but != is_set) {
1291                                                         UI_but_execute(C, but);
1292                                                         if (do_check) {
1293                                                                 ui_but_update_edited(but);
1294                                                         }
1295                                                         changed = true;
1296                                                 }
1297                                         }
1298                                         /* done */
1299
1300                                 }
1301                         }
1302                 }
1303         }
1304         if (changed) {
1305                 /* apply now, not on release (or if handlers are canceled for whatever reason) */
1306                 ui_apply_but_funcs_after(C);
1307         }
1308
1309         return changed;
1310 }
1311
1312 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
1313 {
1314         ARegion *ar = CTX_wm_region(C);
1315         bool do_draw = false;
1316         int xy[2];
1317
1318         /**
1319          * Initialize Locking:
1320          *
1321          * Check if we need to initialize the lock axis by finding if the first
1322          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
1323          */
1324         if (drag_info->is_xy_lock_init == false) {
1325                 /* first store the buttons original coords */
1326                 uiBut *but = ui_but_find_mouse_over_ex(ar, xy_input[0], xy_input[1], true);
1327
1328                 if (but) {
1329                         if (but->flag & UI_BUT_DRAG_LOCK) {
1330                                 const float but_cent_new[2] = {
1331                                         BLI_rctf_cent_x(&but->rect),
1332                                         BLI_rctf_cent_y(&but->rect),
1333                                 };
1334
1335                                 /* check if this is a different button, chances are high the button wont move about :) */
1336                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
1337                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
1338                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
1339                                         {
1340                                                 drag_info->xy_lock[0] = true;
1341                                         }
1342                                         else {
1343                                                 drag_info->xy_lock[1] = true;
1344                                         }
1345                                         drag_info->is_xy_lock_init = true;
1346                                 }
1347                         }
1348                         else {
1349                                 drag_info->is_xy_lock_init = true;
1350                         }
1351                 }
1352         }
1353         /* done with axis locking */
1354
1355
1356         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
1357         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
1358
1359
1360         /* touch all buttons between last mouse coord and this one */
1361         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->xy_last, xy);
1362
1363         if (do_draw) {
1364                 ED_region_tag_redraw(ar);
1365         }
1366
1367         copy_v2_v2_int(drag_info->xy_last, xy);
1368 }
1369
1370 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
1371 {
1372         uiDragToggleHandle *drag_info = userdata;
1373         MEM_freeN(drag_info);
1374 }
1375
1376 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
1377 {
1378         uiDragToggleHandle *drag_info = userdata;
1379         bool done = false;
1380
1381         switch (event->type) {
1382                 case LEFTMOUSE:
1383                 {
1384                         if (event->val == KM_RELEASE) {
1385                                 done = true;
1386                         }
1387                         break;
1388                 }
1389                 case MOUSEMOVE:
1390                 {
1391                         ui_drag_toggle_set(C, drag_info, &event->x);
1392                         break;
1393                 }
1394         }
1395
1396         if (done) {
1397                 wmWindow *win = CTX_wm_window(C);
1398                 ARegion *ar = CTX_wm_region(C);
1399                 uiBut *but = ui_but_find_mouse_over_ex(ar, drag_info->xy_init[0], drag_info->xy_init[1], true);
1400
1401                 if (but) {
1402                         ui_apply_but_undo(but);
1403                 }
1404
1405                 WM_event_remove_ui_handler(
1406                         &win->modalhandlers,
1407                         ui_handler_region_drag_toggle,
1408                         ui_handler_region_drag_toggle_remove,
1409                         drag_info, false);
1410                 ui_handler_region_drag_toggle_remove(C, drag_info);
1411
1412                 WM_event_add_mousemove(C);
1413                 return WM_UI_HANDLER_BREAK;
1414         }
1415         else {
1416                 return WM_UI_HANDLER_CONTINUE;
1417         }
1418 }
1419
1420 static bool ui_but_is_drag_toggle(const uiBut *but)
1421 {
1422         return ((ui_drag_toggle_but_is_supported(but) == true) &&
1423                 /* menu check is importnt so the button dragged over isn't removed instantly */
1424                 (ui_block_is_menu(but->block) == false));
1425 }
1426
1427 #endif  /* USE_DRAG_TOGGLE */
1428
1429
1430 #ifdef USE_ALLSELECT
1431
1432 static bool ui_selectcontext_begin(
1433         bContext *C, uiBut *but, uiSelectContextStore *selctx_data)
1434 {
1435         PointerRNA ptr, lptr, idptr;
1436         PropertyRNA *prop, *lprop;
1437         bool success = false;
1438         int index;
1439
1440         char *path = NULL;
1441         ListBase lb = {NULL};
1442
1443         ptr = but->rnapoin;
1444         prop = but->rnaprop;
1445         index = but->rnaindex;
1446
1447         /* for now don't support whole colors */
1448         if (index == -1)
1449                 return false;
1450
1451         /* if there is a valid property that is editable... */
1452         if (ptr.data && prop) {
1453                 CollectionPointerLink *link;
1454                 bool use_path_from_id;
1455                 int i;
1456
1457                 /* some facts we want to know */
1458                 const bool is_array = RNA_property_array_check(prop);
1459                 const int rna_type = RNA_property_type(prop);
1460
1461                 if (UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path) &&
1462                     !BLI_listbase_is_empty(&lb))
1463                 {
1464                         selctx_data->elems_len = BLI_listbase_count(&lb);
1465                         selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
1466
1467                         for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
1468                                 uiSelectContextElem *other = &selctx_data->elems[i];
1469                                 /* TODO,. de-duplicate copy_to_selected_button */
1470                                 if (link->ptr.data != ptr.data) {
1471                                         if (use_path_from_id) {
1472                                                 /* Path relative to ID. */
1473                                                 lprop = NULL;
1474                                                 RNA_id_pointer_create(link->ptr.id.data, &idptr);
1475                                                 RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
1476                                         }
1477                                         else if (path) {
1478                                                 /* Path relative to elements from list. */
1479                                                 lprop = NULL;
1480                                                 RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
1481                                         }
1482                                         else {
1483                                                 lptr = link->ptr;
1484                                                 lprop = prop;
1485                                         }
1486
1487                                         /* lptr might not be the same as link->ptr! */
1488                                         if ((lptr.data != ptr.data) &&
1489                                             (lprop == prop) &&
1490                                             RNA_property_editable(&lptr, lprop))
1491                                         {
1492                                                 other->ptr = lptr;
1493                                                 if (is_array) {
1494                                                         if (rna_type == PROP_FLOAT) {
1495                                                                 other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
1496                                                         }
1497                                                         else if (rna_type == PROP_INT) {
1498                                                                 other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
1499                                                         }
1500                                                         /* ignored for now */
1501 #if 0
1502                                                         else if (rna_type == PROP_BOOLEAN) {
1503                                                                 other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
1504                                                         }
1505 #endif
1506                                                 }
1507                                                 else {
1508                                                         if (rna_type == PROP_FLOAT) {
1509                                                                 other->val_f = RNA_property_float_get(&lptr, lprop);
1510                                                         }
1511                                                         else if (rna_type == PROP_INT) {
1512                                                                 other->val_i = RNA_property_int_get(&lptr, lprop);
1513                                                         }
1514                                                         /* ignored for now */
1515 #if 0
1516                                                         else if (rna_type == PROP_BOOLEAN) {
1517                                                                 other->val_b = RNA_property_boolean_get(&lptr, lprop);
1518                                                         }
1519                                                         else if (rna_type == PROP_ENUM) {
1520                                                                 other->val_i = RNA_property_enum_get(&lptr, lprop);
1521                                                         }
1522 #endif
1523                                                 }
1524
1525                                                 continue;
1526                                         }
1527                                 }
1528
1529                                 selctx_data->elems_len -= 1;
1530                                 i -= 1;
1531                         }
1532
1533                         success = (selctx_data->elems_len != 0);
1534                 }
1535         }
1536
1537         if (selctx_data->elems_len == 0) {
1538                 MEM_SAFE_FREE(selctx_data->elems);
1539         }
1540
1541         MEM_SAFE_FREE(path);
1542         BLI_freelistN(&lb);
1543
1544         /* caller can clear */
1545         selctx_data->do_free = true;
1546
1547         if (success) {
1548                 but->flag |= UI_BUT_IS_SELECT_CONTEXT;
1549         }
1550
1551         return success;
1552 }
1553
1554 static void ui_selectcontext_end(
1555         uiBut *but, uiSelectContextStore *selctx_data)
1556 {
1557         if (selctx_data->do_free) {
1558                 if (selctx_data->elems) {
1559                         MEM_freeN(selctx_data->elems);
1560                 }
1561         }
1562
1563         but->flag &= ~UI_BUT_IS_SELECT_CONTEXT;
1564 }
1565
1566 static void ui_selectcontext_apply(
1567         bContext *C, uiBut *but, uiSelectContextStore *selctx_data,
1568         const double value, const double value_orig)
1569 {
1570         if (selctx_data->elems) {
1571                 PropertyRNA *prop = but->rnaprop;
1572                 PropertyRNA *lprop = but->rnaprop;
1573                 int index = but->rnaindex;
1574                 int i;
1575                 const bool use_delta = (selctx_data->is_copy == false);
1576
1577                 union {
1578                         bool  b;
1579                         int   i;
1580                         float f;
1581                         PointerRNA p;
1582                 } delta, min, max;
1583
1584                 const bool is_array = RNA_property_array_check(prop);
1585                 const int rna_type = RNA_property_type(prop);
1586
1587                 if (rna_type == PROP_FLOAT) {
1588                         delta.f = use_delta ? (value - value_orig) : value;
1589                         RNA_property_float_range(&but->rnapoin, prop, &min.f, &max.f);
1590                 }
1591                 else if (rna_type == PROP_INT) {
1592                         delta.i = use_delta ? ((int)value - (int)value_orig) : (int)value;
1593                         RNA_property_int_range(&but->rnapoin, prop, &min.i, &max.i);
1594                 }
1595                 else if (rna_type == PROP_ENUM) {
1596                         delta.i = RNA_property_enum_get(&but->rnapoin, prop);  /* not a delta infact */
1597                 }
1598                 else if (rna_type == PROP_BOOLEAN) {
1599                         if (is_array) {
1600                                 delta.b = RNA_property_boolean_get_index(&but->rnapoin, prop, index);  /* not a delta infact */
1601                         }
1602                         else {
1603                                 delta.b = RNA_property_boolean_get(&but->rnapoin, prop);  /* not a delta infact */
1604                         }
1605                 }
1606                 else if (rna_type == PROP_POINTER) {
1607                         delta.p = RNA_property_pointer_get(&but->rnapoin, prop);  /* not a delta infact */
1608                 }
1609
1610 #ifdef USE_ALLSELECT_LAYER_HACK
1611                 /* make up for not having 'handle_layer_buttons' */
1612                 {
1613                         PropertySubType subtype = RNA_property_subtype(prop);
1614
1615                         if ((rna_type == PROP_BOOLEAN) &&
1616                             ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER) &&
1617                             is_array &&
1618                             /* could check for 'handle_layer_buttons' */
1619                             but->func)
1620                         {
1621                                 wmWindow *win = CTX_wm_window(C);
1622                                 if (!win->eventstate->shift) {
1623                                         const int len = RNA_property_array_length(&but->rnapoin, prop);
1624                                         bool *tmparray = MEM_callocN(sizeof(bool) * len, __func__);
1625
1626                                         tmparray[index] = true;
1627
1628                                         for (i = 0; i < selctx_data->elems_len; i++) {
1629                                                 uiSelectContextElem *other = &selctx_data->elems[i];
1630                                                 PointerRNA lptr = other->ptr;
1631                                                 RNA_property_boolean_set_array(&lptr, lprop, tmparray);
1632                                                 RNA_property_update(C, &lptr, lprop);
1633                                         }
1634
1635                                         MEM_freeN(tmparray);
1636
1637                                         return;
1638                                 }
1639                         }
1640                 }
1641 #endif
1642
1643                 for (i = 0; i < selctx_data->elems_len; i++) {
1644                         uiSelectContextElem *other = &selctx_data->elems[i];
1645                         PointerRNA lptr = other->ptr;
1646
1647                         if (rna_type == PROP_FLOAT) {
1648                                 float other_value = use_delta ? (other->val_f + delta.f) : delta.f;
1649                                 CLAMP(other_value, min.f, max.f);
1650                                 if (is_array) {
1651                                         RNA_property_float_set_index(&lptr, lprop, index, other_value);
1652                                 }
1653                                 else {
1654                                         RNA_property_float_set(&lptr, lprop, other_value);
1655                                 }
1656                         }
1657                         else if (rna_type == PROP_INT) {
1658                                 int other_value = use_delta ? (other->val_i + delta.i) : delta.i;
1659                                 CLAMP(other_value, min.i, max.i);
1660                                 if (is_array) {
1661                                         RNA_property_int_set_index(&lptr, lprop, index, other_value);
1662                                 }
1663                                 else {
1664                                         RNA_property_int_set(&lptr, lprop, other_value);
1665                                 }
1666                         }
1667                         else if (rna_type == PROP_BOOLEAN) {
1668                                 const bool other_value = delta.b;
1669                                 if (is_array) {
1670                                         RNA_property_boolean_set_index(&lptr, lprop, index, other_value);
1671                                 }
1672                                 else {
1673                                         RNA_property_boolean_set(&lptr, lprop, delta.b);
1674                                 }
1675                         }
1676                         else if (rna_type == PROP_ENUM) {
1677                                 const int other_value = delta.i;
1678                                 BLI_assert(!is_array);
1679                                 RNA_property_enum_set(&lptr, lprop, other_value);
1680                         }
1681                         else if (rna_type == PROP_POINTER) {
1682                                 const PointerRNA other_value = delta.p;
1683                                 RNA_property_pointer_set(&lptr, lprop, other_value);
1684                         }
1685
1686                         RNA_property_update(C, &lptr, prop);
1687                 }
1688         }
1689 }
1690
1691 #endif  /* USE_ALLSELECT */
1692
1693
1694 static bool ui_but_contains_point_px_icon(uiBut *but, ARegion *ar, const wmEvent *event)
1695 {
1696         rcti rect;
1697         int x = event->x, y = event->y;
1698
1699         ui_window_to_block(ar, but->block, &x, &y);
1700
1701         BLI_rcti_rctf_copy(&rect, &but->rect);
1702
1703         if (but->imb || but->type == UI_BTYPE_COLOR) {
1704                 /* use button size itself */
1705         }
1706         else if (but->drawflag & UI_BUT_ICON_LEFT) {
1707                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
1708         }
1709         else {
1710                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
1711                 rect.xmin += delta / 2;
1712                 rect.xmax -= delta / 2;
1713         }
1714
1715         return BLI_rcti_isect_pt(&rect, x, y);
1716 }
1717
1718 static bool ui_but_drag_init(
1719         bContext *C, uiBut *but,
1720         uiHandleButtonData *data, const wmEvent *event)
1721 {
1722         /* prevent other WM gestures to start while we try to drag */
1723         WM_gestures_remove(C);
1724
1725         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold * U.dpi_fac) {
1726
1727                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1728                 data->cancel = true;
1729 #ifdef USE_DRAG_TOGGLE
1730                 if (ui_drag_toggle_but_is_supported(but)) {
1731                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1732                         ARegion *ar_prev;
1733
1734                         /* call here because regular mouse-up event wont run,
1735                          * typically 'button_activate_exit()' handles this */
1736                         ui_apply_but_autokey(C, but);
1737
1738                         drag_info->is_set = ui_drag_toggle_but_is_pushed(but);
1739                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
1740                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
1741                         copy_v2_v2_int(drag_info->xy_init, &event->x);
1742                         copy_v2_v2_int(drag_info->xy_last, &event->x);
1743
1744                         /* needed for toggle drag on popups */
1745                         ar_prev = CTX_wm_region(C);
1746                         CTX_wm_region_set(C, data->region);
1747
1748                         WM_event_add_ui_handler(
1749                                 C, &data->window->modalhandlers,
1750                                 ui_handler_region_drag_toggle,
1751                                 ui_handler_region_drag_toggle_remove,
1752                                 drag_info, WM_HANDLER_BLOCKING);
1753
1754                         CTX_wm_region_set(C, ar_prev);
1755
1756                         /* Initialize alignment for single row/column regions,
1757                          * otherwise we use the relative position of the first other button dragged over. */
1758                         if (ELEM(data->region->regiontype, RGN_TYPE_NAV_BAR, RGN_TYPE_HEADER)) {
1759                                 int lock_axis = -1;
1760                                 if (ELEM(data->region->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
1761                                         lock_axis = 0;
1762                                 }
1763                                 else if (ELEM(data->region->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
1764                                         lock_axis = 1;
1765                                 }
1766                                 if (lock_axis != -1) {
1767                                         drag_info->xy_lock[lock_axis] = true;
1768                                         drag_info->is_xy_lock_init = true;
1769                                 }
1770                         }
1771                 }
1772                 else
1773 #endif
1774                 if (but->type == UI_BTYPE_COLOR) {
1775                         bool valid = false;
1776                         uiDragColorHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1777
1778                         /* TODO support more button pointer types */
1779                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
1780                                 ui_but_v3_get(but, drag_info->color);
1781                                 drag_info->gamma_corrected = true;
1782                                 valid = true;
1783                         }
1784                         else if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR) {
1785                                 ui_but_v3_get(but, drag_info->color);
1786                                 drag_info->gamma_corrected = false;
1787                                 valid = true;
1788                         }
1789                         else if (ELEM(but->pointype, UI_BUT_POIN_FLOAT, UI_BUT_POIN_CHAR)) {
1790                                 ui_but_v3_get(but, drag_info->color);
1791                                 copy_v3_v3(drag_info->color, (float *)but->poin);
1792                                 valid = true;
1793                         }
1794
1795                         if (valid) {
1796                                 WM_event_start_drag(C, ICON_COLOR, WM_DRAG_COLOR, drag_info, 0.0, WM_DRAG_FREE_DATA);
1797                         }
1798                         else {
1799                                 MEM_freeN(drag_info);
1800                                 return false;
1801                         }
1802                 }
1803                 else {
1804                         wmDrag *drag = WM_event_start_drag(
1805                                 C, but->icon, but->dragtype, but->dragpoin,
1806                                 ui_but_value_get(but), WM_DRAG_NOP);
1807
1808                         if (but->imb) {
1809                                 WM_event_drag_image(
1810                                         drag, but->imb, but->imb_scale,
1811                                         BLI_rctf_size_x(&but->rect),
1812                                         BLI_rctf_size_y(&but->rect));
1813                         }
1814                 }
1815                 return true;
1816         }
1817
1818         return false;
1819 }
1820
1821 /* ********************** linklines *********************** */
1822
1823 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
1824 {
1825         ui_apply_but_func(C, but);
1826         data->retval = but->retval;
1827         data->applied = true;
1828 }
1829
1830 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
1831 {
1832         ui_apply_but_func(C, but);
1833         data->retval = but->retval;
1834         data->applied = true;
1835 }
1836
1837 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
1838 {
1839         ui_apply_but_func(C, but);
1840         data->retval = but->retval;
1841         data->applied = true;
1842 }
1843
1844 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1845 {
1846         ui_apply_but_func(C, but);
1847         data->retval = but->retval;
1848         data->applied = true;
1849 }
1850
1851
1852 static void ui_apply_but(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1853 {
1854         char *editstr;
1855         double *editval;
1856         float *editvec;
1857         ColorBand *editcoba;
1858         CurveMapping *editcumap;
1859
1860         data->retval = 0;
1861
1862         /* if we cancel and have not applied yet, there is nothing to do,
1863          * otherwise we have to restore the original value again */
1864         if (data->cancel) {
1865                 if (!data->applied)
1866                         return;
1867
1868                 if (data->str) MEM_freeN(data->str);
1869                 data->str = data->origstr;
1870                 data->origstr = NULL;
1871                 data->value = data->origvalue;
1872                 copy_v3_v3(data->vec, data->origvec);
1873                 /* postpone clearing origdata */
1874         }
1875         else {
1876                 /* we avoid applying interactive edits a second time
1877                  * at the end with the appliedinteractive flag */
1878                 if (interactive) {
1879                         data->applied_interactive = true;
1880                 }
1881                 else if (data->applied_interactive) {
1882                         return;
1883                 }
1884
1885 #ifdef USE_ALLSELECT
1886 #  ifdef USE_DRAG_MULTINUM
1887                 if (but->flag & UI_BUT_DRAG_MULTI) {
1888                         /* pass */
1889                 }
1890                 else
1891 #  endif
1892                 if (data->select_others.elems_len == 0) {
1893                         wmWindow *win = CTX_wm_window(C);
1894                         /* may have been enabled before activating */
1895                         if (data->select_others.is_enabled || IS_ALLSELECT_EVENT(win->eventstate)) {
1896                                 ui_selectcontext_begin(C, but, &data->select_others);
1897                                 data->select_others.is_enabled = true;
1898                         }
1899                 }
1900                 if (data->select_others.elems_len == 0) {
1901                         /* dont check again */
1902                         data->select_others.elems_len = -1;
1903                 }
1904 #endif
1905         }
1906
1907         /* ensures we are writing actual values */
1908         editstr = but->editstr;
1909         editval = but->editval;
1910         editvec = but->editvec;
1911         editcoba = but->editcoba;
1912         editcumap = but->editcumap;
1913         but->editstr = NULL;
1914         but->editval = NULL;
1915         but->editvec = NULL;
1916         but->editcoba = NULL;
1917         but->editcumap = NULL;
1918
1919         /* handle different types */
1920         switch (but->type) {
1921                 case UI_BTYPE_BUT:
1922                         ui_apply_but_BUT(C, but, data);
1923                         break;
1924                 case UI_BTYPE_TEXT:
1925                 case UI_BTYPE_SEARCH_MENU:
1926                         ui_apply_but_TEX(C, but, data);
1927                         break;
1928                 case UI_BTYPE_BUT_TOGGLE:
1929                 case UI_BTYPE_TOGGLE:
1930                 case UI_BTYPE_TOGGLE_N:
1931                 case UI_BTYPE_ICON_TOGGLE:
1932                 case UI_BTYPE_ICON_TOGGLE_N:
1933                 case UI_BTYPE_CHECKBOX:
1934                 case UI_BTYPE_CHECKBOX_N:
1935                         ui_apply_but_TOG(C, but, data);
1936                         break;
1937                 case UI_BTYPE_ROW:
1938                 case UI_BTYPE_LISTROW:
1939                         ui_apply_but_ROW(C, block, but, data);
1940                         break;
1941                 case UI_BTYPE_TAB:
1942                         ui_apply_but_TAB(C, but, data);
1943                         break;
1944                 case UI_BTYPE_SCROLL:
1945                 case UI_BTYPE_GRIP:
1946                 case UI_BTYPE_NUM:
1947                 case UI_BTYPE_NUM_SLIDER:
1948                         ui_apply_but_NUM(C, but, data);
1949                         break;
1950                 case UI_BTYPE_MENU:
1951                 case UI_BTYPE_BLOCK:
1952                 case UI_BTYPE_PULLDOWN:
1953                         ui_apply_but_BLOCK(C, but, data);
1954                         break;
1955                 case UI_BTYPE_COLOR:
1956                         if (data->cancel)
1957                                 ui_apply_but_VEC(C, but, data);
1958                         else
1959                                 ui_apply_but_BLOCK(C, but, data);
1960                         break;
1961                 case UI_BTYPE_BUT_MENU:
1962                         ui_apply_but_BUTM(C, but, data);
1963                         break;
1964                 case UI_BTYPE_UNITVEC:
1965                 case UI_BTYPE_HSVCUBE:
1966                 case UI_BTYPE_HSVCIRCLE:
1967                         ui_apply_but_VEC(C, but, data);
1968                         break;
1969                 case UI_BTYPE_COLORBAND:
1970                         ui_apply_but_COLORBAND(C, but, data);
1971                         break;
1972                 case UI_BTYPE_CURVE:
1973                         ui_apply_but_CURVE(C, but, data);
1974                         break;
1975                 case UI_BTYPE_KEY_EVENT:
1976                 case UI_BTYPE_HOTKEY_EVENT:
1977                         ui_apply_but_BUT(C, but, data);
1978                         break;
1979                 case UI_BTYPE_IMAGE:
1980                         ui_apply_but_IMAGE(C, but, data);
1981                         break;
1982                 case UI_BTYPE_HISTOGRAM:
1983                         ui_apply_but_HISTOGRAM(C, but, data);
1984                         break;
1985                 case UI_BTYPE_WAVEFORM:
1986                         ui_apply_but_WAVEFORM(C, but, data);
1987                         break;
1988                 case UI_BTYPE_TRACK_PREVIEW:
1989                         ui_apply_but_TRACKPREVIEW(C, but, data);
1990                         break;
1991                 default:
1992                         break;
1993         }
1994
1995 #ifdef USE_DRAG_MULTINUM
1996         if (data->multi_data.has_mbuts) {
1997                 if ((data->multi_data.init == BUTTON_MULTI_INIT_ENABLE) &&
1998                     (data->multi_data.skip == false))
1999                 {
2000                         if (data->cancel) {
2001                                 ui_multibut_restore(C, data, block);
2002                         }
2003                         else {
2004                                 ui_multibut_states_apply(C, data, block);
2005                         }
2006                 }
2007         }
2008 #endif
2009
2010 #ifdef USE_ALLSELECT
2011         ui_selectcontext_apply(C, but, &data->select_others, data->value, data->origvalue);
2012 #endif
2013
2014         if (data->cancel) {
2015                 data->origvalue = 0.0;
2016                 zero_v3(data->origvec);
2017         }
2018
2019         but->editstr = editstr;
2020         but->editval = editval;
2021         but->editvec = editvec;
2022         but->editcoba = editcoba;
2023         but->editcumap = editcumap;
2024 }
2025
2026 /* ******************* drop event ********************  */
2027
2028 /* only call if event type is EVT_DROP */
2029 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
2030 {
2031         wmDrag *wmd;
2032         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
2033
2034         for (wmd = drags->first; wmd; wmd = wmd->next) {
2035                 if (wmd->type == WM_DRAG_ID) {
2036                         /* align these types with UI_but_active_drop_name */
2037                         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2038                                 ID *id = WM_drag_ID(wmd, 0);
2039
2040                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2041
2042                                 ui_textedit_string_set(but, data, id->name + 2);
2043
2044                                 if (ELEM(but->type, UI_BTYPE_SEARCH_MENU)) {
2045                                         but->changed = true;
2046                                         ui_searchbox_update(C, data->searchbox, but, true);
2047                                 }
2048
2049                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2050                         }
2051                 }
2052         }
2053
2054 }
2055
2056 /* ******************* copy and paste ********************  */
2057
2058 static bool ui_but_contains_password(uiBut *but)
2059 {
2060         return but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD);
2061 }
2062
2063 static void ui_but_get_pasted_text_from_clipboard(char **buf_paste, int *buf_len)
2064 {
2065         char *text;
2066         int length;
2067         /* get only first line even if the clipboard contains multiple lines */
2068         text = WM_clipboard_text_get_firstline(false, &length);
2069
2070         if (text) {
2071                 *buf_paste = text;
2072                 *buf_len = length;
2073         }
2074         else {
2075                 *buf_paste = MEM_callocN(sizeof(char), __func__);
2076                 *buf_len = 0;
2077         }
2078 }
2079
2080 static int get_but_property_array_length(uiBut *but)
2081 {
2082         return RNA_property_array_length(&but->rnapoin, but->rnaprop);
2083 }
2084
2085 static void ui_but_set_float_array(bContext *C, uiBut *but, uiHandleButtonData *data, float *values, int array_length)
2086 {
2087         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2088
2089         for (int i = 0; i < array_length; i++) {
2090                 RNA_property_float_set_index(&but->rnapoin, but->rnaprop, i, values[i]);
2091         }
2092         if (data) data->value = values[but->rnaindex];
2093
2094         button_activate_state(C, but, BUTTON_STATE_EXIT);
2095 }
2096
2097 static void float_array_to_string(float *values, int array_length, char *output, int output_len_max)
2098 {
2099         /* to avoid buffer overflow attacks; numbers are quite arbitrary */
2100         BLI_assert(output_len_max > 15);
2101         output_len_max -= 10;
2102
2103         int current_index = 0;
2104         output[current_index] = '[';
2105         current_index++;
2106
2107         for (int i = 0; i < array_length; i++) {
2108                 int length = BLI_snprintf(output + current_index, output_len_max - current_index, "%f", values[i]);
2109                 current_index += length;
2110
2111                 if (i < array_length - 1) {
2112                         if (current_index < output_len_max) {
2113                                 output[current_index + 0] = ',';
2114                                 output[current_index + 1] = ' ';
2115                                 current_index += 2;
2116                         }
2117                 }
2118         }
2119
2120         output[current_index + 0] = ']';
2121         output[current_index + 1] = '\0';
2122 }
2123
2124 static void ui_but_copy_numeric_array(uiBut *but, char *output, int output_len_max)
2125 {
2126         int array_length = get_but_property_array_length(but);
2127         float *values = alloca(array_length * sizeof(float));
2128         RNA_property_float_get_array(&but->rnapoin, but->rnaprop, values);
2129         float_array_to_string(values, array_length, output, output_len_max);
2130 }
2131
2132 static bool parse_float_array(char *text, float *values, int expected_length)
2133 {
2134         /* can parse max 4 floats for now */
2135         BLI_assert(0 <= expected_length && expected_length <= 4);
2136
2137         float v[5];
2138         int actual_length = sscanf(text, "[%f, %f, %f, %f, %f]", &v[0], &v[1], &v[2], &v[3], &v[4]);
2139
2140         if (actual_length == expected_length) {
2141                 memcpy(values, v, sizeof(float) * expected_length);
2142                 return true;
2143         }
2144         else {
2145                 return false;
2146         }
2147 }
2148
2149 static void ui_but_paste_numeric_array(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2150 {
2151         int array_length = get_but_property_array_length(but);
2152         if (array_length > 4) {
2153                 // not supported for now
2154                 return;
2155         }
2156
2157         float *values = alloca(sizeof(float) * array_length);
2158
2159         if (parse_float_array(buf_paste, values, array_length)) {
2160                 ui_but_set_float_array(C, but, data, values, array_length);
2161         }
2162         else {
2163                 WM_report(RPT_ERROR, "Expected an array of numbers: [n, n, ...]");
2164         }
2165 }
2166
2167 static void ui_but_copy_numeric_value(uiBut *but, char *output, int output_len_max)
2168 {
2169         /* Get many decimal places, then strip trailing zeros.
2170          * note: too high values start to give strange results */
2171         ui_but_string_get_ex(but, output, output_len_max, UI_PRECISION_FLOAT_MAX, false, NULL);
2172         BLI_str_rstrip_float_zero(output, '\0');
2173 }
2174
2175 static void ui_but_paste_numeric_value(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2176 {
2177         double value;
2178
2179         if (ui_but_string_set_eval_num(C, but, buf_paste, &value)) {
2180                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2181                 data->value = value;
2182                 ui_but_string_set(C, but, buf_paste);
2183                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2184         }
2185         else {
2186                 WM_report(RPT_ERROR, "Expected a number");
2187         }
2188 }
2189
2190 static bool ui_but_has_array_value(uiBut *but)
2191 {
2192         return (but->rnapoin.data && but->rnaprop &&
2193                 ELEM(RNA_property_subtype(but->rnaprop), PROP_COLOR, PROP_TRANSLATION, PROP_DIRECTION,
2194                      PROP_VELOCITY, PROP_ACCELERATION, PROP_MATRIX, PROP_EULER, PROP_QUATERNION, PROP_AXISANGLE,
2195                      PROP_XYZ, PROP_XYZ_LENGTH, PROP_COLOR_GAMMA, PROP_COORDS));
2196 }
2197
2198 static void ui_but_paste_normalized_vector(bContext *C, uiBut *but, char *buf_paste)
2199 {
2200         float xyz[3];
2201         if (parse_float_array(buf_paste, xyz, 3)) {
2202                 if (normalize_v3(xyz) == 0.0f) {
2203                         /* better set Z up then have a zero vector */
2204                         xyz[2] = 1.0;
2205                 }
2206                 ui_but_set_float_array(C, but, NULL, xyz, 3);
2207         }
2208         else {
2209                 WM_report(RPT_ERROR, "Paste expected 3 numbers, formatted: '[n, n, n]'");
2210         }
2211 }
2212
2213 static void ui_but_copy_color(uiBut *but, char *output, int output_len_max)
2214 {
2215         float rgba[4];
2216
2217         if (but->rnaprop && get_but_property_array_length(but) == 4)
2218                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
2219         else
2220                 rgba[3] = 1.0f;
2221
2222         ui_but_v3_get(but, rgba);
2223
2224         /* convert to linear color to do compatible copy between gamma and non-gamma */
2225         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2226                 srgb_to_linearrgb_v3_v3(rgba, rgba);
2227
2228         float_array_to_string(rgba, 4, output, output_len_max);
2229 }
2230
2231 static void ui_but_paste_color(bContext *C, uiBut *but, char *buf_paste)
2232 {
2233         float rgba[4];
2234         if (parse_float_array(buf_paste, rgba, 4)) {
2235                 if (but->rnaprop) {
2236                         /* Assume linear colors in buffer. */
2237                         if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
2238                                 linearrgb_to_srgb_v3_v3(rgba, rgba);
2239                         }
2240
2241                         /* Some color properties are RGB, not RGBA. */
2242                         int array_len = get_but_property_array_length(but);
2243                         BLI_assert(ELEM(array_len, 3, 4));
2244                         ui_but_set_float_array(C, but, NULL, rgba, array_len);
2245                 }
2246         }
2247         else {
2248                 WM_report(RPT_ERROR, "Paste expected 4 numbers, formatted: '[n, n, n, n]'");
2249         }
2250 }
2251
2252 static void ui_but_copy_text(uiBut *but, char *output, int output_len_max)
2253 {
2254         ui_but_string_get(but, output, output_len_max);
2255 }
2256
2257 static void ui_but_paste_text(bContext *C, uiBut *but, uiHandleButtonData *data, char *buf_paste)
2258 {
2259         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2260         ui_textedit_string_set(but, but->active, buf_paste);
2261
2262         if (but->type == UI_BTYPE_SEARCH_MENU) {
2263                 but->changed = true;
2264                 ui_searchbox_update(C, data->searchbox, but, true);
2265         }
2266
2267         button_activate_state(C, but, BUTTON_STATE_EXIT);
2268 }
2269
2270 static void ui_but_copy_colorband(uiBut *but)
2271 {
2272         if (but->poin != NULL) {
2273                 memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
2274         }
2275 }
2276
2277 static void ui_but_paste_colorband(bContext *C, uiBut *but, uiHandleButtonData *data)
2278 {
2279         if (but_copypaste_coba.tot != 0) {
2280                 if (!but->poin)
2281                         but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
2282
2283                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2284                 memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
2285                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2286         }
2287 }
2288
2289 static void ui_but_copy_curvemapping(uiBut *but)
2290 {
2291         if (but->poin != NULL) {
2292                 but_copypaste_curve_alive = true;
2293                 curvemapping_free_data(&but_copypaste_curve);
2294                 curvemapping_copy_data(&but_copypaste_curve, (CurveMapping *) but->poin);
2295         }
2296 }
2297
2298 static void ui_but_paste_curvemapping(bContext *C, uiBut *but)
2299 {
2300         if (but_copypaste_curve_alive) {
2301                 if (!but->poin)
2302                         but->poin = MEM_callocN(sizeof(CurveMapping), "curvemapping");
2303
2304                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2305                 curvemapping_free_data((CurveMapping *) but->poin);
2306                 curvemapping_copy_data((CurveMapping *) but->poin, &but_copypaste_curve);
2307                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2308         }
2309 }
2310
2311 static void ui_but_copy_operator(bContext *C, uiBut *but, char *output, int output_len_max)
2312 {
2313         PointerRNA *opptr;
2314         opptr = UI_but_operator_ptr_get(but);
2315
2316         char *str;
2317         str = WM_operator_pystring_ex(C, NULL, false, true, but->optype, opptr);
2318         BLI_strncpy(output, str, output_len_max);
2319         MEM_freeN(str);
2320 }
2321
2322 static void ui_but_copy_menu(uiBut *but, char *output, int output_len_max)
2323 {
2324         MenuType *mt = UI_but_menutype_get(but);
2325         if (mt) {
2326                 BLI_snprintf(output, output_len_max, "bpy.ops.wm.call_menu(name=\"%s\")", mt->idname);
2327         }
2328 }
2329
2330 static void ui_but_copy(bContext *C, uiBut *but, const bool copy_array)
2331 {
2332         if (ui_but_contains_password(but)) {
2333                 return;
2334         }
2335
2336         /* Arbitrary large value (allow for paths: 'PATH_MAX') */
2337         char buf[4096] = {0};
2338         const int buf_max_len = sizeof(buf);
2339
2340         /* Left false for copying internal data (color-band for eg). */
2341         bool is_buf_set = false;
2342
2343         bool has_required_data = !(but->poin == NULL && but->rnapoin.data == NULL);
2344
2345         switch (but->type) {
2346                 case UI_BTYPE_NUM:
2347                 case UI_BTYPE_NUM_SLIDER:
2348                         if (!has_required_data) break;
2349                         if (copy_array && ui_but_has_array_value(but)) {
2350                                 ui_but_copy_numeric_array(but, buf, buf_max_len);
2351                         }
2352                         else {
2353                                 ui_but_copy_numeric_value(but, buf, buf_max_len);
2354                         }
2355                         is_buf_set = true;
2356                         break;
2357
2358                 case UI_BTYPE_UNITVEC:
2359                         if (!has_required_data) break;
2360                         ui_but_copy_numeric_array(but, buf, buf_max_len);
2361                         is_buf_set = true;
2362                         break;
2363
2364                 case UI_BTYPE_COLOR:
2365                         if (!has_required_data) break;
2366                         ui_but_copy_color(but, buf, buf_max_len);
2367                         is_buf_set = true;
2368                         break;
2369
2370                 case UI_BTYPE_TEXT:
2371                 case UI_BTYPE_SEARCH_MENU:
2372                         if (!has_required_data) break;
2373                         ui_but_copy_text(but, buf, buf_max_len);
2374                         is_buf_set = true;
2375                         break;
2376
2377                 case UI_BTYPE_COLORBAND:
2378                         ui_but_copy_colorband(but);
2379                         break;
2380
2381                 case UI_BTYPE_CURVE:
2382                         ui_but_copy_curvemapping(but);
2383                         break;
2384
2385                 case UI_BTYPE_BUT:
2386                         ui_but_copy_operator(C, but, buf, buf_max_len);
2387                         is_buf_set = true;
2388                         break;
2389
2390                 case UI_BTYPE_MENU:
2391                 case UI_BTYPE_PULLDOWN:
2392                         ui_but_copy_menu(but, buf, buf_max_len);
2393                         is_buf_set = true;
2394                         break;
2395
2396                 default:
2397                         break;
2398         }
2399
2400         if (is_buf_set) {
2401                 WM_clipboard_text_set(buf, 0);
2402         }
2403 }
2404
2405 static void ui_but_paste(bContext *C, uiBut *but, uiHandleButtonData *data, const bool paste_array)
2406 {
2407         BLI_assert((but->flag & UI_BUT_DISABLED) == 0); /* caller should check */
2408
2409         int buf_paste_len = 0;
2410         char *buf_paste;
2411         ui_but_get_pasted_text_from_clipboard(&buf_paste, &buf_paste_len);
2412
2413         bool has_required_data = !(but->poin == NULL && but->rnapoin.data == NULL);
2414
2415         switch (but->type) {
2416                 case UI_BTYPE_NUM:
2417                 case UI_BTYPE_NUM_SLIDER:
2418                         if (!has_required_data) break;
2419                         if (paste_array && ui_but_has_array_value(but)) {
2420                                 ui_but_paste_numeric_array(C, but, data, buf_paste);
2421                         }
2422                         else {
2423                                 ui_but_paste_numeric_value(C, but, data, buf_paste);
2424                         }
2425                         break;
2426
2427                 case UI_BTYPE_UNITVEC:
2428                         if (!has_required_data) break;
2429                         ui_but_paste_normalized_vector(C, but, buf_paste);
2430                         break;
2431
2432                 case UI_BTYPE_COLOR:
2433                         if (!has_required_data) break;
2434                         ui_but_paste_color(C, but, buf_paste);
2435                         break;
2436
2437                 case UI_BTYPE_TEXT:
2438                 case UI_BTYPE_SEARCH_MENU:
2439                         if (!has_required_data) break;
2440                         ui_but_paste_text(C, but, data, buf_paste);
2441                         break;
2442
2443                 case UI_BTYPE_COLORBAND:
2444                         ui_but_paste_colorband(C, but, data);
2445                         break;
2446
2447                 case UI_BTYPE_CURVE:
2448                         ui_but_paste_curvemapping(C, but);
2449                         break;
2450
2451                 default:
2452                         break;
2453         }
2454
2455         MEM_freeN((void *)buf_paste);
2456 }
2457
2458 /**
2459  * Password Text
2460  * =============
2461  *
2462  * Functions to convert password strings that should not be displayed
2463  * to asterisk representation (e.g. 'mysecretpasswd' -> '*************')
2464  *
2465  * It converts every UTF-8 character to an asterisk, and also remaps
2466  * the cursor position and selection start/end.
2467  *
2468  * \note: remapping is used, because password could contain UTF-8 characters.
2469  *
2470  */
2471
2472 static int ui_text_position_from_hidden(uiBut *but, int pos)
2473 {
2474         const char *strpos, *butstr;
2475         int i;
2476
2477         butstr = (but->editstr) ? but->editstr : but->drawstr;
2478
2479         for (i = 0, strpos = butstr; i < pos; i++)
2480                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
2481
2482         return (strpos - butstr);
2483 }
2484
2485 static int ui_text_position_to_hidden(uiBut *but, int pos)
2486 {
2487         const char *butstr = (but->editstr) ? but->editstr : but->drawstr;
2488         return BLI_strnlen_utf8(butstr, pos);
2489 }
2490
2491 void ui_but_text_password_hide(char password_str[UI_MAX_PASSWORD_STR], uiBut *but, const bool restore)
2492 {
2493         char *butstr;
2494
2495         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
2496                 return;
2497
2498         butstr = (but->editstr) ? but->editstr : but->drawstr;
2499
2500         if (restore) {
2501                 /* restore original string */
2502                 BLI_strncpy(butstr, password_str, UI_MAX_PASSWORD_STR);
2503
2504                 /* remap cursor positions */
2505                 if (but->pos >= 0) {
2506                         but->pos = ui_text_position_from_hidden(but, but->pos);
2507                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
2508                         but->selend = ui_text_position_from_hidden(but, but->selend);
2509                 }
2510         }
2511         else {
2512                 /* convert text to hidden text using asterisks (e.g. pass -> ****) */
2513                 const size_t len = BLI_strlen_utf8(butstr);
2514
2515                 /* remap cursor positions */
2516                 if (but->pos >= 0) {
2517                         but->pos = ui_text_position_to_hidden(but, but->pos);
2518                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
2519                         but->selend = ui_text_position_to_hidden(but, but->selend);
2520                 }
2521
2522                 /* save original string */
2523                 BLI_strncpy(password_str, butstr, UI_MAX_PASSWORD_STR);
2524                 memset(butstr, '*', len);
2525                 butstr[len] = '\0';
2526         }
2527 }
2528
2529 static void ui_but_text_clear(bContext *C, uiBut *but, uiHandleButtonData *data)
2530 {
2531         /* most likely NULL, but let's check, and give it temp zero string */
2532         if (!data->str) {
2533                 data->str = MEM_callocN(1, "temp str");
2534         }
2535         data->str[0] = 0;
2536
2537         ui_apply_but_TEX(C, but, data);
2538         button_activate_state(C, but, BUTTON_STATE_EXIT);
2539 }
2540
2541
2542 /* ************* in-button text selection/editing ************* */
2543
2544 static void ui_textedit_string_ensure_max_length(uiBut *but, uiHandleButtonData *data, int maxlen)
2545 {
2546         BLI_assert(data->is_str_dynamic);
2547         BLI_assert(data->str == but->editstr);
2548
2549         if (maxlen > data->maxlen) {
2550                 data->str = but->editstr = MEM_reallocN(data->str, sizeof(char) * maxlen);
2551                 data->maxlen = maxlen;
2552         }
2553 }
2554
2555 static void ui_textedit_string_set(uiBut *but, uiHandleButtonData *data, const char *str)
2556 {
2557         if (data->is_str_dynamic) {
2558                 ui_textedit_string_ensure_max_length(but, data, strlen(str) + 1);
2559         }
2560
2561         if (ui_but_is_utf8(but)) {
2562                 BLI_strncpy_utf8(data->str, str, data->maxlen);
2563         }
2564         else {
2565                 BLI_strncpy(data->str, str, data->maxlen);
2566         }
2567 }
2568
2569
2570 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
2571 {
2572         char *str = data->str;
2573         const int len = strlen(str);
2574         bool changed = false;
2575         if (but->selsta != but->selend && len) {
2576                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
2577                 changed = true;
2578         }
2579
2580         but->pos = but->selend = but->selsta;
2581         return changed;
2582 }
2583
2584 /**
2585  * \param x  Screen space cursor location - #wmEvent.x
2586  *
2587  * \note ``but->block->aspect`` is used here, so drawing button style is getting scaled too.
2588  */
2589 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
2590 {
2591         uiStyle *style = UI_style_get();  // XXX pass on as arg
2592         uiFontStyle *fstyle = &style->widget;
2593         const float aspect = but->block->aspect;
2594         const short fstyle_points_prev = fstyle->points;
2595
2596         float startx = but->rect.xmin;
2597         float starty_dummy = 0.0f;
2598         char password_str[UI_MAX_PASSWORD_STR];
2599         /* treat 'str_last' as null terminator for str, no need to modify in-place */
2600         const char *str = but->editstr, *str_last;
2601
2602         ui_block_to_window_fl(data->region, but->block, &startx, &starty_dummy);
2603
2604         ui_fontscale(&fstyle->points, aspect);
2605
2606         UI_fontstyle_set(fstyle);
2607
2608         if (fstyle->kerning == 1) /* for BLF_width */
2609                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2610
2611         ui_but_text_password_hide(password_str, but, false);
2612
2613         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2614                 if (but->flag & UI_HAS_ICON) {
2615                         startx += UI_DPI_ICON_SIZE / aspect;
2616                 }
2617         }
2618         /* but this extra .05 makes clicks inbetween characters feel nicer */
2619         startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit) / aspect;
2620
2621         /* mouse dragged outside the widget to the left */
2622         if (x < startx) {
2623                 int i = but->ofs;
2624
2625                 str_last = &str[but->ofs];
2626
2627                 while (i > 0) {
2628                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &i)) {
2629                                 /* 0.25 == scale factor for less sensitivity */
2630                                 if (BLF_width(fstyle->uifont_id, str + i, (str_last - str) - i) > (startx - x) * 0.25f) {
2631                                         break;
2632                                 }
2633                         }
2634                         else {
2635                                 break; /* unlikely but possible */
2636                         }
2637                 }
2638                 but->ofs = i;
2639                 but->pos = but->ofs;
2640         }
2641         /* mouse inside the widget, mouse coords mapped in widget space */
2642         else {  /* (x >= startx) */
2643                 int pos_i;
2644
2645                 /* keep track of previous distance from the cursor to the char */
2646                 float cdist, cdist_prev = 0.0f;
2647                 short pos_prev;
2648
2649                 str_last = &str[strlen(str)];
2650
2651                 but->pos = pos_prev = ((str_last - str) - but->ofs);
2652
2653                 while (true) {
2654                         cdist = startx + BLF_width(fstyle->uifont_id, str + but->ofs, (str_last - str) - but->ofs);
2655
2656                         /* check if position is found */
2657                         if (cdist < x) {
2658                                 /* check is previous location was in fact closer */
2659                                 if ((x - cdist) > (cdist_prev - x)) {
2660                                         but->pos = pos_prev;
2661                                 }
2662                                 break;
2663                         }
2664                         cdist_prev = cdist;
2665                         pos_prev   = but->pos;
2666                         /* done with tricky distance checks */
2667
2668                         pos_i = but->pos;
2669                         if (but->pos <= 0) break;
2670                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &pos_i)) {
2671                                 but->pos = pos_i;
2672                                 str_last = &str[but->pos + but->ofs];
2673                         }
2674                         else {
2675                                 break; /* unlikely but possible */
2676                         }
2677                 }
2678                 but->pos += but->ofs;
2679                 if (but->pos < 0) but->pos = 0;
2680         }
2681
2682         if (fstyle->kerning == 1)
2683                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2684
2685         ui_but_text_password_hide(password_str, but, true);
2686
2687         fstyle->points = fstyle_points_prev;
2688 }
2689
2690 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
2691 {
2692         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
2693         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
2694
2695         ui_textedit_set_cursor_pos(but, data, x);
2696
2697         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
2698         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
2699
2700         ui_but_update(but);
2701 }
2702
2703 /**
2704  * This is used for both utf8 and ascii
2705  *
2706  * For unicode buttons, \a buf is treated as unicode.
2707  */
2708 static bool ui_textedit_insert_buf(
2709         uiBut *but, uiHandleButtonData *data,
2710         const char *buf, int buf_len)
2711 {
2712         int len = strlen(data->str);
2713         int len_new = len - (but->selend - but->selsta) + 1;
2714         bool changed = false;
2715
2716         if (data->is_str_dynamic) {
2717                 ui_textedit_string_ensure_max_length(but, data, len_new + buf_len);
2718         }
2719
2720         if (len_new <= data->maxlen) {
2721                 char *str = data->str;
2722                 size_t step = buf_len;
2723
2724                 /* type over the current selection */
2725                 if ((but->selend - but->selsta) > 0) {
2726                         changed = ui_textedit_delete_selection(but, data);
2727                         len = strlen(str);
2728                 }
2729
2730                 if ((len + step >= data->maxlen) && (data->maxlen - (len + 1) > 0)) {
2731                         if (ui_but_is_utf8(but)) {
2732                                 /* shorten 'step' to a utf8 aligned size that fits  */
2733                                 BLI_strnlen_utf8_ex(buf, data->maxlen - (len + 1), &step);
2734                         }
2735                         else {
2736                                 step = data->maxlen - (len + 1);
2737                         }
2738                 }
2739
2740                 if (step && (len + step < data->maxlen)) {
2741                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
2742                         memcpy(&str[but->pos], buf, step * sizeof(char));
2743                         but->pos += step;
2744                         changed = true;
2745                 }
2746         }
2747
2748         return changed;
2749 }
2750
2751 static bool ui_textedit_insert_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
2752 {
2753         char buf[2] = {ascii, '\0'};
2754
2755         if (ui_but_is_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
2756                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
2757                        __func__, (int)(unsigned char)ascii);
2758
2759                 return false;
2760         }
2761
2762         /* in some cases we want to allow invalid utf8 chars */
2763         return ui_textedit_insert_buf(but, data, buf, 1);
2764 }
2765
2766 static void ui_textedit_move(
2767         uiBut *but, uiHandleButtonData *data, eStrCursorJumpDirection direction,
2768         const bool select, eStrCursorJumpType jump)
2769 {
2770         const char *str = data->str;
2771         const int len = strlen(str);
2772         const int pos_prev = but->pos;
2773         const bool has_sel = (but->selend - but->selsta) > 0;
2774
2775         ui_but_update(but);
2776
2777         /* special case, quit selection and set cursor */
2778         if (has_sel && !select) {
2779                 if (jump == STRCUR_JUMP_ALL) {
2780                         but->selsta = but->selend = but->pos = direction ? len : 0;
2781                 }
2782                 else {
2783                         if (direction) {
2784                                 but->selsta = but->pos = but->selend;
2785                         }
2786                         else {
2787                                 but->pos = but->selend = but->selsta;
2788                         }
2789                 }
2790                 data->selextend = EXTEND_NONE;
2791         }
2792         else {
2793                 int pos_i = but->pos;
2794                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
2795                 but->pos = pos_i;
2796
2797                 if (select) {
2798                         /* existing selection */
2799                         if (has_sel) {
2800
2801                                 if (data->selextend == EXTEND_NONE) {
2802                                         data->selextend = EXTEND_RIGHT;
2803                                 }
2804
2805                                 if (direction) {
2806                                         if (data->selextend == EXTEND_RIGHT) {
2807                                                 but->selend = but->pos;
2808                                         }
2809                                         else {
2810                                                 but->selsta = but->pos;
2811                                         }
2812                                 }
2813                                 else {
2814                                         if (data->selextend == EXTEND_LEFT) {
2815                                                 but->selsta = but->pos;
2816                                         }
2817                                         else {
2818                                                 but->selend = but->pos;
2819                                         }
2820                                 }
2821
2822                                 if (but->selend < but->selsta) {
2823                                         SWAP(short, but->selsta, but->selend);
2824                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
2825                                 }
2826
2827                         } /* new selection */
2828                         else {
2829                                 if (direction) {
2830                                         data->selextend = EXTEND_RIGHT;
2831                                         but->selend = but->pos;
2832                                         but->selsta = pos_prev;
2833                                 }
2834                                 else {
2835                                         data->selextend = EXTEND_LEFT;
2836                                         but->selend = pos_prev;
2837                                         but->selsta = but->pos;
2838                                 }
2839                         }
2840                 }
2841         }
2842 }
2843
2844 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, eStrCursorJumpType jump)
2845 {
2846         char *str = data->str;
2847         const int len = strlen(str);
2848
2849         bool changed = false;
2850
2851         if (jump == STRCUR_JUMP_ALL) {
2852                 if (len) changed = true;
2853                 str[0] = '\0';
2854                 but->pos = 0;
2855         }
2856         else if (direction) { /* delete */
2857                 if ((but->selend - but->selsta) > 0) {
2858                         changed = ui_textedit_delete_selection(but, data);
2859                 }
2860                 else if (but->pos >= 0 && but->pos < len) {
2861                         int pos = but->pos;
2862                         int step;
2863                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2864                         step = pos - but->pos;
2865                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - (but->pos + step));
2866                         changed = true;
2867                 }
2868         }
2869         else { /* backspace */
2870                 if (len != 0) {
2871                         if ((but->selend - but->selsta) > 0) {
2872                                 changed = ui_textedit_delete_selection(but, data);
2873                         }
2874                         else if (but->pos > 0) {
2875                                 int pos = but->pos;
2876                                 int step;
2877
2878                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2879                                 step = but->pos - pos;
2880                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
2881                                 but->pos -= step;
2882                                 changed = true;
2883                         }
2884                 }
2885         }
2886
2887         return changed;
2888 }
2889
2890 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
2891 {
2892         char *str;
2893         int changed;
2894
2895         str = data->str;
2896
2897         if (data->searchbox)
2898                 changed = ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
2899         else
2900                 changed = but->autocomplete_func(C, str, but->autofunc_arg);
2901
2902         but->pos = strlen(str);
2903         but->selsta = but->selend = but->pos;
2904
2905         return changed;
2906 }
2907
2908 /* mode for ui_textedit_copypaste() */
2909 enum {
2910         UI_TEXTEDIT_PASTE = 1,
2911         UI_TEXTEDIT_COPY,
2912         UI_TEXTEDIT_CUT
2913 };
2914
2915 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
2916 {
2917         char *pbuf;
2918         bool changed = false;
2919         int buf_len;
2920
2921         /* paste */
2922         if (mode == UI_TEXTEDIT_PASTE) {
2923                 /* extract the first line from the clipboard */
2924                 pbuf = WM_clipboard_text_get_firstline(false, &buf_len);
2925
2926                 if (pbuf) {
2927                         if (ui_but_is_utf8(but)) {
2928                                 buf_len -= BLI_utf8_invalid_strip(pbuf, (size_t)buf_len);
2929                         }
2930
2931                         ui_textedit_insert_buf(but, data, pbuf, buf_len);
2932
2933                         changed = true;
2934
2935                         MEM_freeN(pbuf);
2936                 }
2937         }
2938         /* cut & copy */
2939         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
2940                 /* copy the contents to the copypaste buffer */
2941                 int sellen = but->selend - but->selsta;
2942                 char *buf = MEM_mallocN(sizeof(char) * (sellen + 1), "ui_textedit_copypaste");
2943
2944                 BLI_strncpy(buf, data->str + but->selsta, sellen + 1);
2945                 WM_clipboard_text_set(buf, 0);
2946                 MEM_freeN(buf);
2947
2948                 /* for cut only, delete the selection afterwards */
2949                 if (mode == UI_TEXTEDIT_CUT) {
2950                         if ((but->selend - but->selsta) > 0) {
2951                                 changed = ui_textedit_delete_selection(but, data);
2952                         }
2953                 }
2954         }
2955
2956         return changed;
2957 }
2958
2959 #ifdef WITH_INPUT_IME
2960 /* enable ime, and set up uibut ime data */
2961 static void ui_textedit_ime_begin(wmWindow *win, uiBut *UNUSED(but))
2962 {
2963         /* XXX Is this really needed? */
2964         int x, y;
2965
2966         BLI_assert(win->ime_data == NULL);
2967
2968         /* enable IME and position to cursor, it's a trick */
2969         x = win->eventstate->x;
2970         /* flip y and move down a bit, prevent the IME panel cover the edit button */
2971         y = win->eventstate->y - 12;
2972
2973         wm_window_IME_begin(win, x, y, 0, 0, true);
2974 }
2975
2976 /* disable ime, and clear uibut ime data */
2977 static void ui_textedit_ime_end(wmWindow *win, uiBut *UNUSED(but))
2978 {
2979         wm_window_IME_end(win);
2980 }
2981
2982 void ui_but_ime_reposition(uiBut *but, int x, int y, bool complete)
2983 {
2984         BLI_assert(but->active);
2985
2986         ui_region_to_window(but->active->region, &x, &y);
2987         wm_window_IME_begin(but->active->window, x, y - 4, 0, 0, complete);
2988 }
2989
2990 wmIMEData *ui_but_ime_data_get(uiBut *but)
2991 {
2992         if (but->active && but->active->window) {
2993                 return but->active->window->ime_data;
2994         }
2995         else {
2996                 return NULL;
2997         }
2998 }
2999 #endif  /* WITH_INPUT_IME */
3000
3001 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
3002 {
3003         wmWindow *win = CTX_wm_window(C);
3004         int len;
3005         const bool is_num_but = ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER);
3006         bool no_zero_strip = false;
3007
3008         if (data->str) {
3009                 MEM_freeN(data->str);
3010                 data->str = NULL;
3011         }
3012
3013 #ifdef USE_DRAG_MULTINUM
3014         /* this can happen from multi-drag */
3015         if (data->applied_interactive) {
3016                 /* remove any small changes so canceling edit doesn't restore invalid value: T40538 */
3017                 data->cancel = true;
3018                 ui_apply_but(C, but->block, but, data, true);
3019                 data->cancel = false;
3020
3021                 data->applied_interactive = false;
3022         }
3023 #endif
3024
3025 #ifdef USE_ALLSELECT
3026         if (is_num_but) {
3027                 if (IS_ALLSELECT_EVENT(win->eventstate)) {
3028                         data->select_others.is_enabled = true;
3029                         data->select_others.is_copy = true;
3030
3031                 }
3032         }
3033 #endif
3034
3035         /* retrieve string */
3036         data->maxlen = ui_but_string_get_max_length(but);
3037         if (data->maxlen != 0) {
3038                 data->str = MEM_callocN(sizeof(char) * data->maxlen, "textedit str");
3039                 /* We do not want to truncate precision to default here, it's nice to show value,
3040                  * not to edit it - way too much precision is lost then. */
3041                 ui_but_string_get_ex(but, data->str, data->maxlen, UI_PRECISION_FLOAT_MAX, true, &no_zero_strip);
3042         }
3043         else {
3044                 data->is_str_dynamic = true;
3045                 data->str = ui_but_string_get_dynamic(but, &data->maxlen);
3046         }
3047
3048         if (ui_but_is_float(but) && !ui_but_is_unit(but) && !ui_but_anim_expression_get(but, NULL, 0) && !no_zero_strip) {
3049                 BLI_str_rstrip_float_zero(data->str, '\0');
3050         }
3051
3052         if (is_num_but) {
3053                 BLI_assert(data->is_str_dynamic == false);
3054                 ui_but_convert_to_unit_alt_name(but, data->str, data->maxlen);
3055         }
3056
3057         /* won't change from now on */
3058         len = strlen(data->str);
3059
3060         data->origstr = BLI_strdupn(data->str, len);
3061         data->selextend = EXTEND_NONE;
3062         data->selstartx = 0.0f;
3063
3064         /* set cursor pos to the end of the text */
3065         but->editstr = data->str;
3066         but->pos = len;
3067         but->selsta = 0;
3068         but->selend = len;
3069
3070         /* optional searchbox */
3071         if (but->type ==  UI_BTYPE_SEARCH_MENU) {
3072                 data->searchbox = but->search_create_func(C, data->region, but);
3073                 ui_searchbox_update(C, data->searchbox, but, true); /* true = reset */
3074         }
3075
3076         /* reset alert flag (avoid confusion, will refresh on exit) */
3077         but->flag &= ~UI_BUT_REDALERT;
3078
3079         ui_but_update(but);
3080
3081         WM_cursor_modal_set(win, BC_TEXTEDITCURSOR);
3082
3083 #ifdef WITH_INPUT_IME
3084         if (is_num_but == false && BLT_lang_is_ime_supported()) {
3085                 ui_textedit_ime_begin(win, but);
3086         }
3087 #endif
3088 }
3089
3090 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
3091 {
3092         wmWindow *win = CTX_wm_window(C);
3093
3094         if (but) {
3095                 if (ui_but_is_utf8(but)) {
3096                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
3097                         /* not a file?, strip non utf-8 chars */
3098                         if (strip) {
3099                                 /* wont happen often so isn't that annoying to keep it here for a while */
3100                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
3101                         }
3102                 }
3103
3104                 if (data->searchbox) {
3105                         if (data->cancel == false) {
3106                                 if ((ui_searchbox_apply(but, data->searchbox) == false) &&
3107                                     (ui_searchbox_find_index(data->searchbox, but->editstr) == -1))
3108                                 {
3109                                         data->cancel = true;
3110
3111                                         /* ensure menu (popup) too is closed! */
3112                                         data->escapecancel = true;
3113                                 }
3114                         }
3115
3116                         ui_searchbox_free(C, data->searchbox);
3117                         data->searchbox = NULL;
3118                         if (but->free_search_arg) {
3119                                 MEM_SAFE_FREE(but->search_arg);
3120                         }
3121                 }
3122
3123                 but->editstr = NULL;
3124                 but->pos = -1;
3125         }
3126
3127         WM_cursor_modal_restore(win);
3128
3129 #ifdef WITH_INPUT_IME
3130         if (win->ime_data) {
3131                 ui_textedit_ime_end(win, but);
3132         }
3133 #endif