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