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