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