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