UI: Add search-create callback
[blender-staging.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_edited(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) {
846                         ui_but_update_edited(but);
847                 }
848         }
849         else {
850                 
851                 if (value == 0.0) push = 1;
852                 else push = 0;
853                 
854                 if (ELEM(but->type, UI_BTYPE_TOGGLE_N, UI_BTYPE_ICON_TOGGLE_N, UI_BTYPE_CHECKBOX_N)) push = !push;
855                 ui_but_value_set(but, (double)push);
856                 if (but->type == UI_BTYPE_ICON_TOGGLE || but->type == UI_BTYPE_ICON_TOGGLE_N) {
857                         ui_but_update_edited(but);
858                 }
859         }
860         
861         ui_apply_but_func(C, but);
862
863         data->retval = but->retval;
864         data->applied = true;
865 }
866
867 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
868 {
869         uiBut *bt;
870
871         ui_but_value_set(but, but->hardmax);
872
873         ui_apply_but_func(C, but);
874
875         /* states of other row buttons */
876         for (bt = block->buttons.first; bt; bt = bt->next) {
877                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, UI_BTYPE_ROW, UI_BTYPE_LISTROW)) {
878                         ui_but_update_edited(bt);
879                 }
880         }
881
882         data->retval = but->retval;
883         data->applied = true;
884 }
885
886 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
887 {
888         if (!data->str)
889                 return;
890
891         ui_but_string_set(C, but, data->str);
892         ui_but_update_edited(but);
893
894         /* give butfunc a copy of the original text too.
895          * feature used for bone renaming, channels, etc.
896          * afterfunc frees rename_orig */
897         if (data->origstr && (but->flag & UI_BUT_TEXTEDIT_UPDATE)) {
898                 /* In this case, we need to keep origstr available, to restore real org string in case we cancel after
899                  * having typed something already. */
900                 but->rename_orig = BLI_strdup(data->origstr);
901         }
902         else {
903                 but->rename_orig = data->origstr;
904                 data->origstr = NULL;
905         }
906         ui_apply_but_func(C, but);
907
908         data->retval = but->retval;
909         data->applied = true;
910 }
911
912 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
913 {
914         if (data->str) {
915                 if (ui_but_string_set(C, but, data->str)) {
916                         data->value = ui_but_value_get(but);
917                 }
918                 else {
919                         data->cancel = true;
920                         return;
921                 }
922         }
923         else {
924                 ui_but_value_set(but, data->value);
925         }
926
927         ui_but_update_edited(but);
928         ui_apply_but_func(C, but);
929
930         data->retval = but->retval;
931         data->applied = true;
932 }
933
934 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
935 {
936         ui_but_v3_set(but, data->vec);
937         ui_but_update_edited(but);
938         ui_apply_but_func(C, but);
939
940         data->retval = but->retval;
941         data->applied = true;
942 }
943
944 static void ui_apply_but_COLORBAND(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 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
952 {
953         ui_apply_but_func(C, but);
954         data->retval = but->retval;
955         data->applied = true;
956 }
957
958 /* ****************** drag drop code *********************** */
959
960
961 #ifdef USE_DRAG_MULTINUM
962
963 /* small multi-but api */
964 static void ui_multibut_add(uiHandleButtonData *data, uiBut *but)
965 {
966         uiButMultiState *mbut_state;
967
968         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
969         BLI_assert(data->multi_data.has_mbuts);
970
971
972         mbut_state = MEM_callocN(sizeof(*mbut_state), __func__);
973         mbut_state->but = but;
974         mbut_state->origvalue = ui_but_value_get(but);
975
976         BLI_linklist_prepend(&data->multi_data.mbuts, mbut_state);
977
978         UI_butstore_register(data->multi_data.bs_mbuts, &mbut_state->but);
979 }
980
981 static uiButMultiState *ui_multibut_lookup(uiHandleButtonData *data, const uiBut *but)
982 {
983         LinkNode *l;
984
985         for (l = data->multi_data.mbuts; l; l = l->next) {
986                 uiButMultiState *mbut_state;
987
988                 mbut_state = l->link;
989
990                 if (mbut_state->but == but) {
991                         return mbut_state;
992                 }
993         }
994
995         return NULL;
996 }
997
998 static void ui_multibut_restore(bContext *C, uiHandleButtonData *data, uiBlock *block)
999 {
1000         uiBut *but;
1001
1002         for (but = block->buttons.first; but; but = but->next) {
1003                 if (but->flag & UI_BUT_DRAG_MULTI) {
1004                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
1005                         if (mbut_state) {
1006                                 ui_but_value_set(but, mbut_state->origvalue);
1007
1008 #ifdef USE_ALLSELECT
1009                                 if (mbut_state->select_others.elems_len > 0) {
1010                                         ui_selectcontext_apply(
1011                                                 C, but, &mbut_state->select_others,
1012                                                 mbut_state->origvalue, mbut_state->origvalue);
1013                                 }
1014 #else
1015                                 UNUSED_VARS(C);
1016 #endif
1017                         }
1018                 }
1019         }
1020 }
1021
1022 static void ui_multibut_free(uiHandleButtonData *data, uiBlock *block)
1023 {
1024 #ifdef USE_ALLSELECT
1025         if (data->multi_data.mbuts) {
1026                 LinkNode *list = data->multi_data.mbuts;
1027                 while (list) {
1028                         LinkNode *next = list->next;
1029                         uiButMultiState *mbut_state = list->link;
1030
1031                         if (mbut_state->select_others.elems) {
1032                                 MEM_freeN(mbut_state->select_others.elems);
1033                         }
1034
1035                         MEM_freeN(list->link);
1036                         MEM_freeN(list);
1037                         list = next;
1038                 }
1039         }
1040 #else
1041         BLI_linklist_freeN(data->multi_data.mbuts);
1042 #endif
1043
1044         data->multi_data.mbuts = NULL;
1045
1046         if (data->multi_data.bs_mbuts) {
1047                 UI_butstore_free(block, data->multi_data.bs_mbuts);
1048                 data->multi_data.bs_mbuts = NULL;
1049         }
1050 }
1051
1052 static bool ui_multibut_states_tag(uiBut *but_active, uiHandleButtonData *data, const wmEvent *event)
1053 {
1054         uiBut *but;
1055         float seg[2][2];
1056         bool changed = false;
1057
1058         seg[0][0] = data->multi_data.drag_start[0];
1059         seg[0][1] = data->multi_data.drag_start[1];
1060
1061         seg[1][0] = event->x;
1062         seg[1][1] = event->y;
1063
1064         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
1065
1066         ui_window_to_block_fl(data->region, but_active->block, &seg[0][0], &seg[0][1]);
1067         ui_window_to_block_fl(data->region, but_active->block, &seg[1][0], &seg[1][1]);
1068
1069         data->multi_data.has_mbuts = false;
1070
1071         /* follow ui_but_find_mouse_over_ex logic */
1072         for (but = but_active->block->buttons.first; but; but = but->next) {
1073                 bool drag_prev = false;
1074                 bool drag_curr = false;
1075
1076                 /* re-set each time */
1077                 if (but->flag & UI_BUT_DRAG_MULTI) {
1078                         but->flag &= ~UI_BUT_DRAG_MULTI;
1079                         drag_prev = true;
1080                 }
1081
1082                 if (ui_but_is_interactive(but, false)) {
1083
1084                         /* drag checks */
1085                         if (but_active != but) {
1086                                 if (ui_but_is_compatible(but_active, but)) {
1087
1088                                         BLI_assert(but->active == NULL);
1089
1090                                         /* finally check for overlap */
1091                                         if (BLI_rctf_isect_segment(&but->rect, seg[0], seg[1])) {
1092
1093                                                 but->flag |= UI_BUT_DRAG_MULTI;
1094                                                 data->multi_data.has_mbuts = true;
1095                                                 drag_curr = true;
1096                                         }
1097                                 }
1098                         }
1099                 }
1100
1101                 changed |= (drag_prev != drag_curr);
1102         }
1103
1104         return changed;
1105 }
1106
1107 static void ui_multibut_states_create(uiBut *but_active, uiHandleButtonData *data)
1108 {
1109         uiBut *but;
1110
1111         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_SETUP);
1112         BLI_assert(data->multi_data.has_mbuts);
1113
1114         data->multi_data.bs_mbuts = UI_butstore_create(but_active->block);
1115
1116         for (but = but_active->block->buttons.first; but; but = but->next) {
1117                 if (but->flag & UI_BUT_DRAG_MULTI) {
1118                         ui_multibut_add(data, but);
1119                 }
1120         }
1121
1122         /* edit buttons proportionally to eachother
1123          * note: if we mix buttons which are proportional and others which are not,
1124          * this may work a bit strangely */
1125         if (but_active->rnaprop) {
1126                 if ((data->origvalue != 0.0) && (RNA_property_flag(but_active->rnaprop) & PROP_PROPORTIONAL)) {
1127                         data->multi_data.is_proportional = true;
1128                 }
1129         }
1130 }
1131
1132 static void ui_multibut_states_apply(bContext *C, uiHandleButtonData *data, uiBlock *block)
1133 {
1134         ARegion *ar = data->region;
1135         const double value_delta = data->value - data->origvalue;
1136         const double value_scale = data->multi_data.is_proportional ? (data->value / data->origvalue) : 0.0;
1137         uiBut *but;
1138
1139         BLI_assert(data->multi_data.init == BUTTON_MULTI_INIT_ENABLE);
1140
1141         for (but = block->buttons.first; but; but = but->next) {
1142                 if (but->flag & UI_BUT_DRAG_MULTI) {
1143                         /* mbut_states for delta */
1144                         uiButMultiState *mbut_state = ui_multibut_lookup(data, but);
1145
1146                         if (mbut_state) {
1147                                 void *active_back;
1148
1149                                 ui_but_execute_begin(C, ar, but, &active_back);
1150
1151 #ifdef USE_ALLSELECT
1152                                 if (data->select_others.is_enabled) {
1153                                         /* init once! */
1154                                         if (mbut_state->select_others.elems_len == 0) {
1155                                                 ui_selectcontext_begin(C, but, &mbut_state->select_others);
1156                                         }
1157                                         if (mbut_state->select_others.elems_len == 0) {
1158                                                 mbut_state->select_others.elems_len = -1;
1159                                         }
1160                                 }
1161
1162                                 /* needed so we apply the right deltas */
1163                                 but->active->origvalue = mbut_state->origvalue;
1164                                 but->active->select_others = mbut_state->select_others;
1165                                 but->active->select_others.do_free = false;
1166 #endif
1167
1168                                 BLI_assert(active_back == NULL);
1169                                 /* no need to check 'data->state' here */
1170                                 if (data->str) {
1171                                         /* entering text (set all) */
1172                                         but->active->value = data->value;
1173                                         ui_but_string_set(C, but, data->str);
1174                                 }
1175                                 else {
1176                                         /* dragging (use delta) */
1177                                         if (data->multi_data.is_proportional) {
1178                                                 but->active->value = mbut_state->origvalue * value_scale;
1179                                         }
1180                                         else {
1181                                                 but->active->value = mbut_state->origvalue + value_delta;
1182                                         }
1183
1184                                         /* clamp based on soft limits, see: T40154 */
1185                                         CLAMP(but->active->value, (double)but->softmin, (double)but->softmax);
1186                                 }
1187                                 ui_but_execute_end(C, ar, but, active_back);
1188                         }
1189                         else {
1190                                 /* highly unlikely */
1191                                 printf("%s: cant find button\n", __func__);
1192                         }
1193                         /* end */
1194
1195                 }
1196         }
1197 }
1198
1199 #endif  /* USE_DRAG_MULTINUM */
1200
1201
1202 #ifdef USE_DRAG_TOGGLE
1203
1204 typedef struct uiDragToggleHandle {
1205         /* init */
1206         bool is_init;
1207         bool is_set;
1208         float but_cent_start[2];
1209         eButType but_type_start;
1210
1211         bool xy_lock[2];
1212         int  xy_init[2];
1213         int  xy_last[2];
1214 } uiDragToggleHandle;
1215
1216 static bool ui_drag_toggle_set_xy_xy(
1217         bContext *C, ARegion *ar, const bool is_set, const eButType but_type_start,
1218         const int xy_src[2], const int xy_dst[2])
1219 {
1220         /* popups such as layers won't re-evaluate on redraw */
1221         const bool do_check = (ar->regiontype == RGN_TYPE_TEMPORARY);
1222         bool changed = false;
1223         uiBlock *block;
1224
1225         for (block = ar->uiblocks.first; block; block = block->next) {
1226                 uiBut *but;
1227
1228                 float xy_a_block[2] = {UNPACK2(xy_src)};
1229                 float xy_b_block[2] = {UNPACK2(xy_dst)};
1230
1231                 ui_window_to_block_fl(ar, block, &xy_a_block[0], &xy_a_block[1]);
1232                 ui_window_to_block_fl(ar, block, &xy_b_block[0], &xy_b_block[1]);
1233
1234                 for (but = block->buttons.first; but; but = but->next) {
1235                         /* Note: ctrl is always true here because (at least for now) we always want to consider text control
1236                          *       in this case, even when not embossed. */
1237                         if (ui_but_is_interactive(but, true)) {
1238                                 if (BLI_rctf_isect_segment(&but->rect, xy_a_block, xy_b_block)) {
1239
1240                                         /* execute the button */
1241                                         if (ui_but_is_bool(but) && but->type == but_type_start) {
1242                                                 /* is it pressed? */
1243                                                 bool is_set_but = ui_but_is_pushed(but);
1244                                                 BLI_assert(ui_but_is_bool(but) == true);
1245                                                 if (is_set_but != is_set) {
1246                                                         UI_but_execute(C, but);
1247                                                         if (do_check) {
1248                                                                 ui_but_update_edited(but);
1249                                                         }
1250                                                         changed = true;
1251                                                 }
1252                                         }
1253                                         /* done */
1254
1255                                 }
1256                         }
1257                 }
1258         }
1259
1260         return changed;
1261 }
1262
1263 static void ui_drag_toggle_set(bContext *C, uiDragToggleHandle *drag_info, const int xy_input[2])
1264 {
1265         ARegion *ar = CTX_wm_region(C);
1266         bool do_draw = false;
1267         int xy[2];
1268
1269         /**
1270          * Initialize Locking:
1271          *
1272          * Check if we need to initialize the lock axis by finding if the first
1273          * button we mouse over is X or Y aligned, then lock the mouse to that axis after.
1274          */
1275         if (drag_info->is_init == false) {
1276                 /* first store the buttons original coords */
1277                 uiBut *but = ui_but_find_mouse_over_ex(ar, xy_input[0], xy_input[1], true);
1278
1279                 if (but) {
1280                         if (but->flag & UI_BUT_DRAG_LOCK) {
1281                                 const float but_cent_new[2] = {BLI_rctf_cent_x(&but->rect),
1282                                                                BLI_rctf_cent_y(&but->rect)};
1283
1284                                 /* check if this is a different button, chances are high the button wont move about :) */
1285                                 if (len_manhattan_v2v2(drag_info->but_cent_start, but_cent_new) > 1.0f) {
1286                                         if (fabsf(drag_info->but_cent_start[0] - but_cent_new[0]) <
1287                                             fabsf(drag_info->but_cent_start[1] - but_cent_new[1]))
1288                                         {
1289                                                 drag_info->xy_lock[0] = true;
1290                                         }
1291                                         else {
1292                                                 drag_info->xy_lock[1] = true;
1293                                         }
1294                                         drag_info->is_init = true;
1295                                 }
1296                         }
1297                         else {
1298                                 drag_info->is_init = true;
1299                         }
1300                 }
1301         }
1302         /* done with axis locking */
1303
1304
1305         xy[0] = (drag_info->xy_lock[0] == false) ? xy_input[0] : drag_info->xy_last[0];
1306         xy[1] = (drag_info->xy_lock[1] == false) ? xy_input[1] : drag_info->xy_last[1];
1307
1308
1309         /* touch all buttons between last mouse coord and this one */
1310         do_draw = ui_drag_toggle_set_xy_xy(C, ar, drag_info->is_set, drag_info->but_type_start, drag_info->xy_last, xy);
1311
1312         if (do_draw) {
1313                 ED_region_tag_redraw(ar);
1314         }
1315
1316         copy_v2_v2_int(drag_info->xy_last, xy);
1317 }
1318
1319 static void ui_handler_region_drag_toggle_remove(bContext *UNUSED(C), void *userdata)
1320 {
1321         uiDragToggleHandle *drag_info = userdata;
1322         MEM_freeN(drag_info);
1323 }
1324
1325 static int ui_handler_region_drag_toggle(bContext *C, const wmEvent *event, void *userdata)
1326 {
1327         uiDragToggleHandle *drag_info = userdata;
1328         bool done = false;
1329
1330         switch (event->type) {
1331                 case LEFTMOUSE:
1332                 {
1333                         if (event->val != KM_PRESS) {
1334                                 done = true;
1335                         }
1336                         break;
1337                 }
1338                 case MOUSEMOVE:
1339                 {
1340                         ui_drag_toggle_set(C, drag_info, &event->x);
1341                         break;
1342                 }
1343         }
1344
1345         if (done) {
1346                 wmWindow *win = CTX_wm_window(C);
1347                 ARegion *ar = CTX_wm_region(C);
1348                 uiBut *but = ui_but_find_mouse_over_ex(ar, drag_info->xy_init[0], drag_info->xy_init[1], true);
1349
1350                 if (but) {
1351                         ui_apply_but_undo(but);
1352                 }
1353
1354                 WM_event_remove_ui_handler(&win->modalhandlers,
1355                                            ui_handler_region_drag_toggle,
1356                                            ui_handler_region_drag_toggle_remove,
1357                                            drag_info, false);
1358                 ui_handler_region_drag_toggle_remove(C, drag_info);
1359
1360                 WM_event_add_mousemove(C);
1361                 return WM_UI_HANDLER_BREAK;
1362         }
1363         else {
1364                 return WM_UI_HANDLER_CONTINUE;
1365         }
1366 }
1367
1368 static bool ui_but_is_drag_toggle(const uiBut *but)
1369 {
1370         return ((ui_but_is_bool(but) == true) &&
1371                 /* menu check is importnt so the button dragged over isn't removed instantly */
1372                 (ui_block_is_menu(but->block) == false));
1373 }
1374
1375 #endif  /* USE_DRAG_TOGGLE */
1376
1377
1378 #ifdef USE_ALLSELECT
1379
1380 static bool ui_selectcontext_begin(
1381         bContext *C, uiBut *but, uiSelectContextStore *selctx_data)
1382 {
1383         PointerRNA ptr, lptr, idptr;
1384         PropertyRNA *prop, *lprop;
1385         bool success = false;
1386         int index;
1387
1388         char *path = NULL;
1389         ListBase lb = {NULL};
1390
1391         ptr = but->rnapoin;
1392         prop = but->rnaprop;
1393         index = but->rnaindex;
1394
1395         /* for now don't support whole colors */
1396         if (index == -1)
1397                 return false;
1398
1399         /* if there is a valid property that is editable... */
1400         if (ptr.data && prop) {
1401                 CollectionPointerLink *link;
1402                 bool use_path_from_id;
1403                 int i;
1404
1405                 /* some facts we want to know */
1406                 const bool is_array = RNA_property_array_check(prop);
1407                 const int rna_type = RNA_property_type(prop);
1408
1409                 if (!UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path)) {
1410                         goto finally;
1411                 }
1412
1413                 selctx_data->elems_len = BLI_listbase_count(&lb);
1414                 if (selctx_data->elems_len == 0) {
1415                         goto finally;
1416                 }
1417
1418                 selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
1419
1420                 for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
1421                         uiSelectContextElem *other = &selctx_data->elems[i];
1422                         /* TODO,. de-duplicate copy_to_selected_button */
1423                         if (link->ptr.data != ptr.data) {
1424                                 if (use_path_from_id) {
1425                                         /* Path relative to ID. */
1426                                         lprop = NULL;
1427                                         RNA_id_pointer_create(link->ptr.id.data, &idptr);
1428                                         RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
1429                                 }
1430                                 else if (path) {
1431                                         /* Path relative to elements from list. */
1432                                         lprop = NULL;
1433                                         RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
1434                                 }
1435                                 else {
1436                                         lptr = link->ptr;
1437                                         lprop = prop;
1438                                 }
1439
1440                                 /* lptr might not be the same as link->ptr! */
1441                                 if ((lptr.data != ptr.data) &&
1442                                     (lprop == prop) &&
1443                                     RNA_property_editable(&lptr, lprop))
1444                                 {
1445                                         other->ptr = lptr;
1446                                         if (is_array) {
1447                                                 if (rna_type == PROP_FLOAT) {
1448                                                         other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
1449                                                 }
1450                                                 else if (rna_type == PROP_INT) {
1451                                                         other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
1452                                                 }
1453                                                 /* ignored for now */
1454 #if 0
1455                                                 else if (rna_type == PROP_BOOLEAN) {
1456                                                         other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
1457                                                 }
1458 #endif
1459                                         }
1460                                         else {
1461                                                 if (rna_type == PROP_FLOAT) {
1462                                                         other->val_f = RNA_property_float_get(&lptr, lprop);
1463                                                 }
1464                                                 else if (rna_type == PROP_INT) {
1465                                                         other->val_i = RNA_property_int_get(&lptr, lprop);
1466                                                 }
1467                                                 /* ignored for now */
1468 #if 0
1469                                                 else if (rna_type == PROP_BOOLEAN) {
1470                                                         other->val_b = RNA_property_boolean_get(&lptr, lprop);
1471                                                 }
1472                                                 else if (rna_type == PROP_ENUM) {
1473                                                         other->val_i = RNA_property_enum_get(&lptr, lprop);
1474                                                 }
1475 #endif
1476                                         }
1477
1478                                         continue;
1479                                 }
1480                         }
1481
1482                         selctx_data->elems_len -= 1;
1483                         i -= 1;
1484                 }
1485         }
1486
1487         success = (selctx_data->elems_len != 0);
1488
1489 finally:
1490         if (selctx_data->elems_len == 0) {
1491                 MEM_SAFE_FREE(selctx_data->elems);
1492         }
1493
1494         MEM_SAFE_FREE(path);
1495         BLI_freelistN(&lb);
1496
1497         /* caller can clear */
1498         selctx_data->do_free = true;
1499
1500         if (success) {
1501                 but->flag |= UI_BUT_IS_SELECT_CONTEXT;
1502         }
1503
1504         return success;
1505 }
1506
1507 static void ui_selectcontext_end(
1508         uiBut *but, uiSelectContextStore *selctx_data)
1509 {
1510         if (selctx_data->do_free) {
1511                 if (selctx_data->elems) {
1512                         MEM_freeN(selctx_data->elems);
1513                 }
1514         }
1515
1516         but->flag &= ~UI_BUT_IS_SELECT_CONTEXT;
1517 }
1518
1519 static void ui_selectcontext_apply(
1520         bContext *C, uiBut *but, uiSelectContextStore *selctx_data,
1521         const double value, const double value_orig)
1522 {
1523         if (selctx_data->elems) {
1524                 PropertyRNA *prop = but->rnaprop;
1525                 PropertyRNA *lprop = but->rnaprop;
1526                 int index = but->rnaindex;
1527                 int i;
1528                 const bool use_delta = (selctx_data->is_copy == false);
1529
1530                 union {
1531                         bool  b;
1532                         int   i;
1533                         float f;
1534                 } delta, min, max;
1535
1536                 const bool is_array = RNA_property_array_check(prop);
1537                 const int rna_type = RNA_property_type(prop);
1538
1539                 if (rna_type == PROP_FLOAT) {
1540                         delta.f = use_delta ? (value - value_orig) : value;
1541                         RNA_property_float_range(&but->rnapoin, prop, &min.f, &max.f);
1542                 }
1543                 else if (rna_type == PROP_INT) {
1544                         delta.i = use_delta ? ((int)value - (int)value_orig) : (int)value;
1545                         RNA_property_int_range(&but->rnapoin, prop, &min.i, &max.i);
1546                 }
1547                 else if (rna_type == PROP_ENUM) {
1548                         delta.i = RNA_property_enum_get(&but->rnapoin, prop);  /* not a delta infact */
1549                 }
1550                 else if (rna_type == PROP_BOOLEAN) {
1551                         if (is_array) {
1552                                 delta.b = RNA_property_boolean_get_index(&but->rnapoin, prop, index);  /* not a delta infact */
1553                         }
1554                         else {
1555                                 delta.b = RNA_property_boolean_get(&but->rnapoin, prop);  /* not a delta infact */
1556                         }
1557                 }
1558
1559 #ifdef USE_ALLSELECT_LAYER_HACK
1560                 /* make up for not having 'handle_layer_buttons' */
1561                 {
1562                         PropertySubType subtype = RNA_property_subtype(prop);
1563
1564                         if ((rna_type == PROP_BOOLEAN) &&
1565                             ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER) &&
1566                             is_array &&
1567                             /* could check for 'handle_layer_buttons' */
1568                             but->func)
1569                         {
1570                                 wmWindow *win = CTX_wm_window(C);
1571                                 if (!win->eventstate->shift) {
1572                                         const int len = RNA_property_array_length(&but->rnapoin, prop);
1573                                         int *tmparray = MEM_callocN(sizeof(int) * len, __func__);
1574
1575                                         tmparray[index] = true;
1576
1577                                         for (i = 0; i < selctx_data->elems_len; i++) {
1578                                                 uiSelectContextElem *other = &selctx_data->elems[i];
1579                                                 PointerRNA lptr = other->ptr;
1580                                                 RNA_property_boolean_set_array(&lptr, lprop, tmparray);
1581                                                 RNA_property_update(C, &lptr, lprop);
1582                                         }
1583
1584                                         MEM_freeN(tmparray);
1585
1586                                         return;
1587                                 }
1588                         }
1589                 }
1590 #endif
1591
1592                 for (i = 0; i < selctx_data->elems_len; i++) {
1593                         uiSelectContextElem *other = &selctx_data->elems[i];
1594                         PointerRNA lptr = other->ptr;
1595
1596                         if (rna_type == PROP_FLOAT) {
1597                                 float other_value = use_delta ? (other->val_f + delta.f) : delta.f;
1598                                 CLAMP(other_value, min.f, max.f);
1599                                 if (is_array) {
1600                                         RNA_property_float_set_index(&lptr, lprop, index, other_value);
1601                                 }
1602                                 else {
1603                                         RNA_property_float_set(&lptr, lprop, other_value);
1604                                 }
1605                         }
1606                         else if (rna_type == PROP_INT) {
1607                                 int other_value = use_delta ? (other->val_i + delta.i) : delta.i;
1608                                 CLAMP(other_value, min.i, max.i);
1609                                 if (is_array) {
1610                                         RNA_property_int_set_index(&lptr, lprop, index, other_value);
1611                                 }
1612                                 else {
1613                                         RNA_property_int_set(&lptr, lprop, other_value);
1614                                 }
1615                         }
1616                         else if (rna_type == PROP_BOOLEAN) {
1617                                 const bool other_value = delta.b;
1618                                 if (is_array) {
1619                                         RNA_property_boolean_set_index(&lptr, lprop, index, other_value);
1620                                 }
1621                                 else {
1622                                         RNA_property_boolean_set(&lptr, lprop, delta.b);
1623                                 }
1624                         }
1625                         else if (rna_type == PROP_ENUM) {
1626                                 const int other_value = delta.i;
1627                                 BLI_assert(!is_array);
1628                                 RNA_property_enum_set(&lptr, lprop, other_value);
1629                         }
1630
1631                         RNA_property_update(C, &lptr, prop);
1632                 }
1633         }
1634 }
1635
1636 #endif  /* USE_ALLSELECT */
1637
1638
1639 static bool ui_but_contains_point_px_icon(uiBut *but, ARegion *ar, const wmEvent *event)
1640 {
1641         rcti rect;
1642         int x = event->x, y = event->y;
1643         
1644         ui_window_to_block(ar, but->block, &x, &y);
1645         
1646         BLI_rcti_rctf_copy(&rect, &but->rect);
1647         
1648         if (but->imb || but->type == UI_BTYPE_COLOR) {
1649                 /* use button size itself */
1650         }
1651         else if (but->drawflag & UI_BUT_ICON_LEFT) {
1652                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
1653         }
1654         else {
1655                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
1656                 rect.xmin += delta / 2;
1657                 rect.xmax -= delta / 2;
1658         }
1659         
1660         return BLI_rcti_isect_pt(&rect, x, y);
1661 }
1662
1663 static bool ui_but_drag_init(bContext *C, uiBut *but, uiHandleButtonData *data, const wmEvent *event)
1664 {
1665         /* prevent other WM gestures to start while we try to drag */
1666         WM_gestures_remove(C);
1667
1668         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
1669
1670                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1671                 data->cancel = true;
1672 #ifdef USE_DRAG_TOGGLE
1673                 if (ui_but_is_bool(but)) {
1674                         uiDragToggleHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1675                         ARegion *ar_prev;
1676
1677                         /* call here because regular mouse-up event wont run,
1678                          * typically 'button_activate_exit()' handles this */
1679                         ui_apply_but_autokey(C, but);
1680
1681                         drag_info->is_set = ui_but_is_pushed(but);
1682                         drag_info->but_cent_start[0] = BLI_rctf_cent_x(&but->rect);
1683                         drag_info->but_cent_start[1] = BLI_rctf_cent_y(&but->rect);
1684                         drag_info->but_type_start = but->type;
1685                         copy_v2_v2_int(drag_info->xy_init, &event->x);
1686                         copy_v2_v2_int(drag_info->xy_last, &event->x);
1687
1688                         /* needed for toggle drag on popups */
1689                         ar_prev = CTX_wm_region(C);
1690                         CTX_wm_region_set(C, data->region);
1691
1692                         WM_event_add_ui_handler(
1693                                 C, &data->window->modalhandlers,
1694                                 ui_handler_region_drag_toggle,
1695                                 ui_handler_region_drag_toggle_remove,
1696                                 drag_info, WM_HANDLER_BLOCKING);
1697
1698                         CTX_wm_region_set(C, ar_prev);
1699                 }
1700                 else
1701 #endif
1702                 if (but->type == UI_BTYPE_COLOR) {
1703                         bool valid = false;
1704                         uiDragColorHandle *drag_info = MEM_callocN(sizeof(*drag_info), __func__);
1705
1706                         /* TODO support more button pointer types */
1707                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
1708                                 RNA_property_float_get_array(&but->rnapoin, but->rnaprop, drag_info->color);
1709                                 drag_info->gamma_corrected = true;
1710                                 valid = true;
1711                         }
1712                         else if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR) {
1713                                 RNA_property_float_get_array(&but->rnapoin, but->rnaprop, drag_info->color);
1714                                 drag_info->gamma_corrected = false;
1715                                 valid = true;
1716                         }
1717                         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1718                                 copy_v3_v3(drag_info->color, (float *)but->poin);
1719                                 valid = true;
1720                         }
1721                         else if (but->pointype == UI_BUT_POIN_CHAR) {
1722                                 rgb_uchar_to_float(drag_info->color, (unsigned char *)but->poin);
1723                                 valid = true;
1724                         }
1725
1726                         if (valid) {
1727                                 WM_event_start_drag(C, ICON_COLOR, WM_DRAG_COLOR, drag_info, 0.0, WM_DRAG_FREE_DATA);
1728                         }
1729                         else {
1730                                 MEM_freeN(drag_info);
1731                                 return false;
1732                         }
1733                 }
1734                 else {
1735                         wmDrag *drag;
1736
1737                         drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_but_value_get(but), WM_DRAG_NOP);
1738                         if (but->imb)
1739                                 WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
1740                 }
1741                 return true;
1742         }
1743         
1744         return false;
1745 }
1746
1747 /* ********************** linklines *********************** */
1748
1749 static void ui_linkline_remove_active(uiBlock *block)
1750 {
1751         uiBut *but;
1752         uiLink *link;
1753         uiLinkLine *line, *nline;
1754         int a, b;
1755
1756         for (but = block->buttons.first; but; but = but->next) {
1757                 if (but->type == UI_BTYPE_LINK && but->link) {
1758                         for (line = but->link->lines.first; line; line = nline) {
1759                                 nline = line->next;
1760                                 
1761                                 if (line->flag & UI_SELECT) {
1762                                         BLI_remlink(&but->link->lines, line);
1763                                         
1764                                         link = line->from->link;
1765                                         
1766                                         /* are there more pointers allowed? */
1767                                         if (link->ppoin) {
1768                                                 
1769                                                 if (*(link->totlink) == 1) {
1770                                                         *(link->totlink) = 0;
1771                                                         MEM_freeN(*(link->ppoin));
1772                                                         *(link->ppoin) = NULL;
1773                                                 }
1774                                                 else {
1775                                                         b = 0;
1776                                                         for (a = 0; a < (*(link->totlink)); a++) {
1777                                                                 
1778                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
1779                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1780                                                                         b++;
1781                                                                 }
1782                                                         }
1783                                                         (*(link->totlink))--;
1784                                                 }
1785                                         }
1786                                         else {
1787                                                 *(link->poin) = NULL;
1788                                         }
1789                                         
1790                                         MEM_freeN(line);
1791                                 }
1792                         }
1793                 }
1794         }
1795 }
1796
1797
1798 static uiLinkLine *ui_but_find_link(uiBut *from, uiBut *to)
1799 {
1800         uiLinkLine *line;
1801         uiLink *link;
1802         
1803         link = from->link;
1804         if (link) {
1805                 for (line = link->lines.first; line; line = line->next) {
1806                         if (line->from == from && line->to == to) {
1807                                 return line;
1808                         }
1809                 }
1810         }
1811         return NULL;
1812 }
1813
1814 /* XXX BAD BAD HACK, fixme later **************** */
1815 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
1816 static void ui_but_smart_controller_add(bContext *C, uiBut *from, uiBut *to)
1817 {
1818         Object *ob = NULL;
1819         bSensor *sens_iter;
1820         bActuator *act_to, *act_iter;
1821         bController *cont;
1822         bController ***sens_from_links;
1823         uiBut *tmp_but;
1824
1825         uiLink *link = from->link;
1826
1827         PointerRNA props_ptr, object_ptr;
1828         
1829         if (link->ppoin)
1830                 sens_from_links = (bController ***)(link->ppoin);
1831         else return;
1832
1833         act_to = (bActuator *)(to->poin);
1834
1835         /* (1) get the object */
1836         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
1837         {
1838                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
1839                         if (&(sens_iter->links) == sens_from_links) {
1840                                 ob = ob_iter;
1841                                 break;
1842                         }
1843                 }
1844                 if (ob) break;
1845         } CTX_DATA_END;
1846
1847         if (!ob) return;
1848
1849         /* (2) check if the sensor and the actuator are from the same object */
1850         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
1851                 if (act_iter == act_to)
1852                         break;
1853         }
1854
1855         /* only works if the sensor and the actuator are from the same object */
1856         if (!act_iter) return;
1857         
1858         /* in case the linked controller is not the active one */
1859         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
1860         
1861         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
1862         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
1863
1864         /* (3) add a new controller */
1865         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
1866                 cont = (bController *)ob->controllers.last;
1867                 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... */
1868
1869                 /* (4) link the sensor->controller->actuator */
1870                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
1871                 UI_but_link_set(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
1872                 tmp_but->hardmin = from->link->tocode;
1873                 tmp_but->poin = (char *)cont;
1874
1875                 tmp_but->type = UI_BTYPE_INLINK;
1876                 ui_but_link_add(C, from, tmp_but);
1877
1878                 tmp_but->type = UI_BTYPE_LINK;
1879                 ui_but_link_add(C, tmp_but, to);
1880
1881                 /* (5) garbage collection */
1882                 MEM_freeN(tmp_but->link);
1883                 MEM_freeN(tmp_but);
1884         }
1885         WM_operator_properties_free(&props_ptr);
1886 }
1887
1888 static void ui_but_link_add(bContext *C, uiBut *from, uiBut *to)
1889 {
1890         /* in 'from' we have to add a link to 'to' */
1891         uiLink *link;
1892         uiLinkLine *line;
1893         void **oldppoin;
1894         int a;
1895         
1896         if ((line = ui_but_find_link(from, to))) {
1897                 line->flag |= UI_SELECT;
1898                 ui_linkline_remove_active(from->block);
1899                 return;
1900         }
1901
1902         if (from->type == UI_BTYPE_INLINK && to->type == UI_BTYPE_INLINK) {
1903                 return;
1904         }
1905         else if (from->type == UI_BTYPE_LINK && to->type == UI_BTYPE_INLINK) {
1906                 if (from->link->tocode != (int)to->hardmin) {
1907                         ui_but_smart_controller_add(C, from, to);
1908                         return;
1909                 }
1910         }
1911         else if (from->type == UI_BTYPE_INLINK && to->type == UI_BTYPE_LINK) {
1912                 if (to->link->tocode == (int)from->hardmin) {
1913                         return;
1914                 }
1915         }
1916         
1917         link = from->link;
1918         
1919         /* are there more pointers allowed? */
1920         if (link->ppoin) {
1921                 oldppoin = *(link->ppoin);
1922                 
1923                 (*(link->totlink))++;
1924                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
1925                 
1926                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
1927                         (*(link->ppoin))[a] = oldppoin[a];
1928                 }
1929                 (*(link->ppoin))[a] = to->poin;
1930                 
1931                 if (oldppoin) MEM_freeN(oldppoin);
1932         }
1933         else {
1934                 *(link->poin) = to->poin;
1935         }
1936         
1937 }
1938
1939
1940 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
1941 {
1942         ARegion *ar = CTX_wm_region(C);
1943         uiBut *bt;
1944         
1945         for (bt = but->block->buttons.first; bt; bt = bt->next) {
1946                 if (ui_but_contains_point_px(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
1947                         break;
1948         }
1949         if (bt && bt != but) {
1950                 if (!ELEM(bt->type, UI_BTYPE_LINK, UI_BTYPE_INLINK) || !ELEM(but->type, UI_BTYPE_LINK, UI_BTYPE_INLINK))
1951                         return;
1952                 
1953                 if (but->type == UI_BTYPE_LINK) ui_but_link_add(C, but, bt);
1954                 else ui_but_link_add(C, bt, but);
1955
1956                 ui_apply_but_func(C, but);
1957                 data->retval = but->retval;
1958         }
1959         data->applied = true;
1960 }
1961
1962 static void ui_apply_but_IMAGE(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_HISTOGRAM(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_WAVEFORM(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 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
1984 {
1985         ui_apply_but_func(C, but);
1986         data->retval = but->retval;
1987         data->applied = true;
1988 }
1989
1990
1991 static void ui_apply_but(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, const bool interactive)
1992 {
1993         char *editstr;
1994         double *editval;
1995         float *editvec;
1996         ColorBand *editcoba;
1997         CurveMapping *editcumap;
1998
1999         data->retval = 0;
2000
2001         /* if we cancel and have not applied yet, there is nothing to do,
2002          * otherwise we have to restore the original value again */
2003         if (data->cancel) {
2004                 if (!data->applied)
2005                         return;
2006
2007                 if (data->str) MEM_freeN(data->str);
2008                 data->str = data->origstr;
2009                 data->origstr = NULL;
2010                 data->value = data->origvalue;
2011                 copy_v3_v3(data->vec, data->origvec);
2012                 /* postpone clearing origdata */
2013         }
2014         else {
2015                 /* we avoid applying interactive edits a second time
2016                  * at the end with the appliedinteractive flag */
2017                 if (interactive) {
2018                         data->applied_interactive = true;
2019                 }
2020                 else if (data->applied_interactive) {
2021                         return;
2022                 }
2023
2024 #ifdef USE_ALLSELECT
2025 #  ifdef USE_DRAG_MULTINUM
2026                 if (but->flag & UI_BUT_DRAG_MULTI) {
2027                         /* pass */
2028                 }
2029                 else
2030 #  endif
2031                 if (data->select_others.elems_len == 0) {
2032                         wmWindow *win = CTX_wm_window(C);
2033                         /* may have been enabled before activating */
2034                         if (data->select_others.is_enabled || IS_ALLSELECT_EVENT(win->eventstate)) {
2035                                 ui_selectcontext_begin(C, but, &data->select_others);
2036                                 data->select_others.is_enabled = true;
2037                         }
2038                 }
2039                 if (data->select_others.elems_len == 0) {
2040                         /* dont check again */
2041                         data->select_others.elems_len = -1;
2042                 }
2043 #endif
2044         }
2045
2046         /* ensures we are writing actual values */
2047         editstr = but->editstr;
2048         editval = but->editval;
2049         editvec = but->editvec;
2050         editcoba = but->editcoba;
2051         editcumap = but->editcumap;
2052         but->editstr = NULL;
2053         but->editval = NULL;
2054         but->editvec = NULL;
2055         but->editcoba = NULL;
2056         but->editcumap = NULL;
2057
2058         /* handle different types */
2059         switch (but->type) {
2060                 case UI_BTYPE_BUT:
2061                         ui_apply_but_BUT(C, but, data);
2062                         break;
2063                 case UI_BTYPE_TEXT:
2064                 case UI_BTYPE_SEARCH_MENU:
2065                         ui_apply_but_TEX(C, but, data);
2066                         break;
2067                 case UI_BTYPE_BUT_TOGGLE:
2068                 case UI_BTYPE_TOGGLE:
2069                 case UI_BTYPE_TOGGLE_N:
2070                 case UI_BTYPE_ICON_TOGGLE:
2071                 case UI_BTYPE_ICON_TOGGLE_N:
2072                 case UI_BTYPE_CHECKBOX:
2073                 case UI_BTYPE_CHECKBOX_N:
2074                         ui_apply_but_TOG(C, but, data);
2075                         break;
2076                 case UI_BTYPE_ROW:
2077                 case UI_BTYPE_LISTROW:
2078                         ui_apply_but_ROW(C, block, but, data);
2079                         break;
2080                 case UI_BTYPE_SCROLL:
2081                 case UI_BTYPE_GRIP:
2082                 case UI_BTYPE_NUM:
2083                 case UI_BTYPE_NUM_SLIDER:
2084                         ui_apply_but_NUM(C, but, data);
2085                         break;
2086                 case UI_BTYPE_MENU:
2087                 case UI_BTYPE_BLOCK:
2088                 case UI_BTYPE_PULLDOWN:
2089                         ui_apply_but_BLOCK(C, but, data);
2090                         break;
2091                 case UI_BTYPE_COLOR:
2092                         if (data->cancel)
2093                                 ui_apply_but_VEC(C, but, data);
2094                         else
2095                                 ui_apply_but_BLOCK(C, but, data);
2096                         break;
2097                 case UI_BTYPE_BUT_MENU:
2098                         ui_apply_but_BUTM(C, but, data);
2099                         break;
2100                 case UI_BTYPE_UNITVEC:
2101                 case UI_BTYPE_HSVCUBE:
2102                 case UI_BTYPE_HSVCIRCLE:
2103                         ui_apply_but_VEC(C, but, data);
2104                         break;
2105                 case UI_BTYPE_COLORBAND:
2106                         ui_apply_but_COLORBAND(C, but, data);
2107                         break;
2108                 case UI_BTYPE_CURVE:
2109                         ui_apply_but_CURVE(C, but, data);
2110                         break;
2111                 case UI_BTYPE_KEY_EVENT:
2112                 case UI_BTYPE_HOTKEY_EVENT:
2113                         ui_apply_but_BUT(C, but, data);
2114                         break;
2115                 case UI_BTYPE_LINK:
2116                 case UI_BTYPE_INLINK:
2117                         ui_apply_but_LINK(C, but, data);
2118                         break;
2119                 case UI_BTYPE_IMAGE:
2120                         ui_apply_but_IMAGE(C, but, data);
2121                         break;
2122                 case UI_BTYPE_HISTOGRAM:
2123                         ui_apply_but_HISTOGRAM(C, but, data);
2124                         break;
2125                 case UI_BTYPE_WAVEFORM:
2126                         ui_apply_but_WAVEFORM(C, but, data);
2127                         break;
2128                 case UI_BTYPE_TRACK_PREVIEW:
2129                         ui_apply_but_TRACKPREVIEW(C, but, data);
2130                         break;
2131                 default:
2132                         break;
2133         }
2134
2135 #ifdef USE_DRAG_MULTINUM
2136         if (data->multi_data.has_mbuts) {
2137                 if (data->multi_data.init == BUTTON_MULTI_INIT_ENABLE) {
2138                         if (data->cancel) {
2139                                 ui_multibut_restore(C, data, block);
2140                         }
2141                         else {
2142                                 ui_multibut_states_apply(C, data, block);
2143                         }
2144                 }
2145         }
2146 #endif
2147
2148 #ifdef USE_ALLSELECT
2149         ui_selectcontext_apply(C, but, &data->select_others, data->value, data->origvalue);
2150 #endif
2151
2152         if (data->cancel) {
2153                 data->origvalue = 0.0;
2154                 zero_v3(data->origvec);
2155         }
2156
2157         but->editstr = editstr;
2158         but->editval = editval;
2159         but->editvec = editvec;
2160         but->editcoba = editcoba;
2161         but->editcumap = editcumap;
2162 }
2163
2164 /* ******************* drop event ********************  */
2165
2166 /* only call if event type is EVT_DROP */
2167 static void ui_but_drop(bContext *C, const wmEvent *event, uiBut *but, uiHandleButtonData *data)
2168 {
2169         wmDrag *wmd;
2170         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
2171         
2172         for (wmd = drags->first; wmd; wmd = wmd->next) {
2173                 if (wmd->type == WM_DRAG_ID) {
2174                         /* align these types with UI_but_active_drop_name */
2175                         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2176                                 ID *id = (ID *)wmd->poin;
2177                                 
2178                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2179
2180                                 ui_textedit_string_set(but, data, id->name + 2);
2181
2182                                 if (ELEM(but->type, UI_BTYPE_SEARCH_MENU)) {
2183                                         but->changed = true;
2184                                         ui_searchbox_update(C, data->searchbox, but, true);
2185                                 }
2186
2187                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2188                         }
2189                 }
2190         }
2191         
2192 }
2193
2194 /* ******************* copy and paste ********************  */
2195
2196 static void ui_but_copy_data_path(uiBut *but, const bool full_path)
2197 {
2198         char *id_path;
2199
2200         if (but->rnapoin.id.data == NULL) {
2201                 return;
2202         }
2203
2204         if (full_path) {
2205                 if (but->rnaprop) {
2206                         id_path = RNA_path_full_property_py_ex(&but->rnapoin, but->rnaprop, but->rnaindex, true);
2207                 }
2208                 else {
2209                         id_path = RNA_path_full_struct_py(&but->rnapoin);
2210                 }
2211         }
2212         else {
2213                 id_path = RNA_path_from_ID_to_property(&but->rnapoin, but->rnaprop);
2214         }
2215
2216         if (id_path) {
2217                 WM_clipboard_text_set(id_path, false);
2218                 MEM_freeN(id_path);
2219         }
2220 }
2221
2222 /* c = copy, v = paste */
2223 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
2224 {
2225         int buf_paste_len = 0;
2226         const char *buf_paste = "";
2227         bool buf_paste_alloc = false;
2228         bool show_report = false;  /* use to display errors parsing paste input */
2229
2230         if (mode == 'v' && but->lock  == true) {
2231                 return;
2232         }
2233
2234         if (mode == 'c') {
2235                 /* disallow copying from any passwords */
2236                 if (but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) {
2237                         return;
2238                 }
2239         }
2240
2241         if (mode == 'v') {
2242                 /* extract first line from clipboard in case of multi-line copies */
2243                 const char *buf_paste_test;
2244
2245                 buf_paste_test = WM_clipboard_text_get_firstline(false, &buf_paste_len);
2246                 if (buf_paste_test) {
2247                         buf_paste = buf_paste_test;
2248                         buf_paste_alloc = true;
2249                 }
2250         }
2251
2252         /* No return from here down */
2253
2254
2255         /* numeric value */
2256         if (ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER)) {
2257                 
2258                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2259                         /* pass */
2260                 }
2261                 else if (mode == 'c') {
2262                         /* Get many decimal places, then strip trailing zeros.
2263                          * note: too high values start to give strange results */
2264                         char buf_copy[UI_MAX_DRAW_STR];
2265                         ui_but_string_get_ex(but, buf_copy, sizeof(buf_copy), UI_PRECISION_FLOAT_MAX);
2266                         BLI_str_rstrip_float_zero(buf_copy, '\0');
2267
2268                         WM_clipboard_text_set(buf_copy, 0);
2269                 }
2270                 else {
2271                         double val;
2272
2273                         if (ui_but_string_set_eval_num(C, but, buf_paste, &val)) {
2274                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2275                                 data->value = val;
2276                                 ui_but_string_set(C, but, buf_paste);
2277                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2278                         }
2279                         else {
2280                                 /* evaluating will report errors */
2281                                 show_report = true;
2282                         }
2283                 }
2284         }
2285
2286         /* NORMAL button */
2287         else if (but->type == UI_BTYPE_UNITVEC) {
2288                 float xyz[3];
2289
2290                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2291                         /* pass */
2292                 }
2293                 else if (mode == 'c') {
2294                         char buf_copy[UI_MAX_DRAW_STR];
2295                         ui_but_v3_get(but, xyz);
2296                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f]", xyz[0], xyz[1], xyz[2]);
2297                         WM_clipboard_text_set(buf_copy, 0);
2298                 }
2299                 else {
2300                         if (sscanf(buf_paste, "[%f, %f, %f]", &xyz[0], &xyz[1], &xyz[2]) == 3) {
2301                                 if (normalize_v3(xyz) == 0.0f) {
2302                                         /* better set Z up then have a zero vector */
2303                                         xyz[2] = 1.0;
2304                                 }
2305                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2306                                 ui_but_v3_set(but, xyz);
2307                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2308                         }
2309                         else {
2310                                 WM_report(RPT_ERROR, "Paste expected 3 numbers, formatted: '[n, n, n]'");
2311                                 show_report = true;
2312                         }
2313                 }
2314         }
2315
2316
2317         /* RGB triple */
2318         else if (but->type == UI_BTYPE_COLOR) {
2319                 float rgba[4];
2320                 
2321                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2322                         /* pass */
2323                 }
2324                 else if (mode == 'c') {
2325                         char buf_copy[UI_MAX_DRAW_STR];
2326
2327                         if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
2328                                 rgba[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
2329                         else
2330                                 rgba[3] = 1.0f;
2331                         
2332                         ui_but_v3_get(but, rgba);
2333                         /* convert to linear color to do compatible copy between gamma and non-gamma */
2334                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2335                                 srgb_to_linearrgb_v3_v3(rgba, rgba);
2336
2337                         BLI_snprintf(buf_copy, sizeof(buf_copy), "[%f, %f, %f, %f]", rgba[0], rgba[1], rgba[2], rgba[3]);
2338                         WM_clipboard_text_set(buf_copy, 0);
2339                         
2340                 }
2341                 else {
2342                         if (sscanf(buf_paste, "[%f, %f, %f, %f]", &rgba[0], &rgba[1], &rgba[2], &rgba[3]) == 4) {
2343                                 /* assume linear colors in buffer */
2344                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
2345                                         linearrgb_to_srgb_v3_v3(rgba, rgba);
2346
2347                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2348                                 ui_but_v3_set(but, rgba);
2349                                 if (but->rnaprop && RNA_property_array_length(&but->rnapoin, but->rnaprop) == 4)
2350                                         RNA_property_float_set_index(&but->rnapoin, but->rnaprop, 3, rgba[3]);
2351
2352                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2353                         }
2354                         else {
2355                                 WM_report(RPT_ERROR, "Paste expected 4 numbers, formatted: '[n, n, n, n]'");
2356                                 show_report = true;
2357                         }
2358                 }
2359         }
2360
2361         /* text/string and ID data */
2362         else if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2363                 uiHandleButtonData *active_data = but->active;
2364
2365                 if (but->poin == NULL && but->rnapoin.data == NULL) {
2366                         /* pass */
2367                 }
2368                 else if (mode == 'c') {
2369                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2370                         WM_clipboard_text_set(active_data->str, 0);
2371                         active_data->cancel = true;
2372                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2373                 }
2374                 else {
2375                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2376
2377                         ui_textedit_string_set(but, active_data, buf_paste);
2378
2379                         if (but->type == UI_BTYPE_SEARCH_MENU) {
2380                                 /* else uiSearchboxData.active member is not updated [#26856] */
2381                                 but->changed = true;
2382                                 ui_searchbox_update(C, data->searchbox, but, true);
2383                         }
2384                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2385                 }
2386         }
2387         /* colorband (not supported by system clipboard) */
2388         else if (but->type == UI_BTYPE_COLORBAND) {
2389                 if (mode == 'c') {
2390                         if (but->poin != NULL) {
2391                                 memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
2392                         }
2393                 }
2394                 else {
2395                         if (but_copypaste_coba.tot != 0) {
2396                                 if (!but->poin)
2397                                         but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
2398
2399                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2400                                 memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
2401                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2402                         }
2403                 }
2404         }
2405         else if (but->type == UI_BTYPE_CURVE) {
2406                 if (mode == 'c') {
2407                         if (but->poin != NULL) {
2408                                 but_copypaste_curve_alive = true;
2409                                 curvemapping_free_data(&but_copypaste_curve);
2410                                 curvemapping_copy_data(&but_copypaste_curve, (CurveMapping *) but->poin);
2411                         }
2412                 }
2413                 else {
2414                         if (but_copypaste_curve_alive) {
2415                                 if (!but->poin)
2416                                         but->poin = MEM_callocN(sizeof(CurveMapping), "curvemapping");
2417
2418                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2419                                 curvemapping_free_data((CurveMapping *) but->poin);
2420                                 curvemapping_copy_data((CurveMapping *) but->poin, &but_copypaste_curve);
2421                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2422                         }
2423                 }
2424         }
2425         /* operator button (any type) */
2426         else if (but->optype) {
2427                 if (mode == 'c') {
2428                         PointerRNA *opptr;
2429                         char *str;
2430                         opptr = UI_but_operator_ptr_get(but); /* allocated when needed, the button owns it */
2431
2432                         str = WM_operator_pystring_ex(C, NULL, false, true, but->optype, opptr);
2433
2434                         WM_clipboard_text_set(str, 0);
2435
2436                         MEM_freeN(str);
2437                 }
2438         }
2439         /* menu (any type) */
2440         else if (ELEM(but->type, UI_BTYPE_MENU, UI_BTYPE_PULLDOWN)) {
2441                 MenuType *mt = UI_but_menutype_get(but);
2442                 if (mt) {
2443                         char str[32 + sizeof(mt->idname)];
2444                         BLI_snprintf(str, sizeof(str), "bpy.ops.wm.call_menu(name=\"%s\")", mt->idname);
2445                         WM_clipboard_text_set(str, 0);
2446                 }
2447         }
2448
2449         if (buf_paste_alloc) {
2450                 MEM_freeN((void *)buf_paste);
2451         }
2452
2453         if (show_report) {
2454                 WM_report_banner_show();
2455         }
2456 }
2457
2458 /**
2459  * Password Text
2460  * =============
2461  *
2462  * Functions to convert password strings that should not be displayed
2463  * to asterisk representation (e.g. 'mysecretpasswd' -> '*************')
2464  *
2465  * It converts every UTF-8 character to an asterisk, and also remaps
2466  * the cursor position and selection start/end.
2467  *
2468  * \note: remaping is used, because password could contain UTF-8 characters.
2469  *
2470  */
2471
2472 static int ui_text_position_from_hidden(uiBut *but, int pos)
2473 {
2474         const char *strpos, *butstr;
2475         int i;
2476
2477         butstr = (but->editstr) ? but->editstr : but->drawstr;
2478
2479         for (i = 0, strpos = butstr; i < pos; i++)
2480                 strpos = BLI_str_find_next_char_utf8(strpos, NULL);
2481         
2482         return (strpos - butstr);
2483 }
2484
2485 static int ui_text_position_to_hidden(uiBut *but, int pos)
2486 {
2487         const char *butstr = (but->editstr) ? but->editstr : but->drawstr;
2488         return BLI_strnlen_utf8(butstr, pos);
2489 }
2490
2491 void ui_but_text_password_hide(char password_str[UI_MAX_PASSWORD_STR], uiBut *but, const bool restore)
2492 {
2493         char *butstr;
2494
2495         if (!(but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_PASSWORD))
2496                 return;
2497
2498         butstr = (but->editstr) ? but->editstr : but->drawstr;
2499
2500         if (restore) {
2501                 /* restore original string */
2502                 BLI_strncpy(butstr, password_str, UI_MAX_PASSWORD_STR);
2503
2504                 /* remap cursor positions */
2505                 if (but->pos >= 0) {
2506                         but->pos = ui_text_position_from_hidden(but, but->pos);
2507                         but->selsta = ui_text_position_from_hidden(but, but->selsta);
2508                         but->selend = ui_text_position_from_hidden(but, but->selend);
2509                 }
2510         }
2511         else {
2512                 /* convert text to hidden text using asterisks (e.g. pass -> ****) */
2513                 const size_t len = BLI_strlen_utf8(butstr);
2514
2515                 /* remap cursor positions */
2516                 if (but->pos >= 0) {
2517                         but->pos = ui_text_position_to_hidden(but, but->pos);
2518                         but->selsta = ui_text_position_to_hidden(but, but->selsta);
2519                         but->selend = ui_text_position_to_hidden(but, but->selend);
2520                 }
2521
2522                 /* save original string */
2523                 BLI_strncpy(password_str, butstr, UI_MAX_PASSWORD_STR);
2524                 memset(butstr, '*', len);
2525                 butstr[len] = '\0';
2526         }
2527 }
2528
2529
2530 /* ************* in-button text selection/editing ************* */
2531
2532 static void ui_textedit_string_ensure_max_length(uiBut *but, uiHandleButtonData *data, int maxlen)
2533 {
2534         BLI_assert(data->is_str_dynamic);
2535         BLI_assert(data->str == but->editstr);
2536
2537         if (maxlen > data->maxlen) {
2538                 data->str = but->editstr = MEM_reallocN(data->str, sizeof(char) * maxlen);
2539                 data->maxlen = maxlen;
2540         }
2541 }
2542
2543 static void ui_textedit_string_set(uiBut *but, uiHandleButtonData *data, const char *str)
2544 {
2545         if (data->is_str_dynamic) {
2546                 ui_textedit_string_ensure_max_length(but, data, strlen(str) + 1);
2547         }
2548
2549         if (ui_but_is_utf8(but)) {
2550                 BLI_strncpy_utf8(data->str, str, data->maxlen);
2551         }
2552         else {
2553                 BLI_strncpy(data->str, str, data->maxlen);
2554         }
2555 }
2556
2557
2558 static bool ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
2559 {
2560         char *str = data->str;
2561         const int len = strlen(str);
2562         bool changed = false;
2563         if (but->selsta != but->selend && len) {
2564                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
2565                 changed = true;
2566         }
2567         
2568         but->pos = but->selend = but->selsta;
2569         return changed;
2570 }
2571
2572 /**
2573  * \param x  Screen space cursor location - #wmEvent.x
2574  *
2575  * \note ``but->block->aspect`` is used here, so drawing button style is getting scaled too.
2576  */
2577 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, const float x)
2578 {
2579         uiStyle *style = UI_style_get();  // XXX pass on as arg
2580         uiFontStyle *fstyle = &style->widget;
2581         const float aspect = but->block->aspect;
2582         const short fstyle_points_prev = fstyle->points;
2583
2584         float startx = but->rect.xmin;
2585         float starty_dummy = 0.0f;
2586         char password_str[UI_MAX_PASSWORD_STR];
2587         /* treat 'str_last' as null terminator for str, no need to modify in-place */
2588         const char *str = but->editstr, *str_last;
2589
2590         ui_block_to_window_fl(data->region, but->block, &startx, &starty_dummy);
2591
2592         ui_fontscale(&fstyle->points, aspect);
2593
2594         UI_fontstyle_set(fstyle);
2595
2596         if (fstyle->kerning == 1) /* for BLF_width */
2597                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2598         
2599         ui_but_text_password_hide(password_str, but, false);
2600
2601         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2602                 if (but->flag & UI_HAS_ICON) {
2603                         startx += UI_DPI_ICON_SIZE / aspect;
2604                 }
2605         }
2606         /* but this extra .05 makes clicks inbetween characters feel nicer */
2607         startx += ((UI_TEXT_MARGIN_X + 0.05f) * U.widget_unit) / aspect;
2608         
2609         /* mouse dragged outside the widget to the left */
2610         if (x < startx) {
2611                 int i = but->ofs;
2612
2613                 str_last = &str[but->ofs];
2614                 
2615                 while (i > 0) {
2616                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &i)) {
2617                                 /* 0.25 == scale factor for less sensitivity */
2618                                 if (BLF_width(fstyle->uifont_id, str + i, (str_last - str) - i) > (startx - x) * 0.25f) {
2619                                         break;
2620                                 }
2621                         }
2622                         else {
2623                                 break; /* unlikely but possible */
2624                         }
2625                 }
2626                 but->ofs = i;
2627                 but->pos = but->ofs;
2628         }
2629         /* mouse inside the widget, mouse coords mapped in widget space */
2630         else {  /* (x >= startx) */
2631                 int pos_i;
2632
2633                 /* keep track of previous distance from the cursor to the char */
2634                 float cdist, cdist_prev = 0.0f;
2635                 short pos_prev;
2636                 
2637                 str_last = &str[strlen(str)];
2638
2639                 but->pos = pos_prev = ((str_last - str) - but->ofs);
2640
2641                 while (true) {
2642                         cdist = startx + BLF_width(fstyle->uifont_id, str + but->ofs, (str_last - str) - but->ofs);
2643
2644                         /* check if position is found */
2645                         if (cdist < x) {
2646                                 /* check is previous location was in fact closer */
2647                                 if ((x - cdist) > (cdist_prev - x)) {
2648                                         but->pos = pos_prev;
2649                                 }
2650                                 break;
2651                         }
2652                         cdist_prev = cdist;
2653                         pos_prev   = but->pos;
2654                         /* done with tricky distance checks */
2655
2656                         pos_i = but->pos;
2657                         if (but->pos <= 0) break;
2658                         if (BLI_str_cursor_step_prev_utf8(str, but->ofs, &pos_i)) {
2659                                 but->pos = pos_i;
2660                                 str_last = &str[but->pos + but->ofs];
2661                         }
2662                         else {
2663                                 break; /* unlikely but possible */
2664                         }
2665                 }
2666                 but->pos += but->ofs;
2667                 if (but->pos < 0) but->pos = 0;
2668         }
2669         
2670         if (fstyle->kerning == 1)
2671                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
2672         
2673         ui_but_text_password_hide(password_str, but, true);
2674
2675         fstyle->points = fstyle_points_prev;
2676 }
2677
2678 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, const float x)
2679 {
2680         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
2681         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
2682
2683         ui_textedit_set_cursor_pos(but, data, x);
2684
2685         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
2686         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
2687
2688         ui_but_update(but);
2689 }
2690
2691 /**
2692  * This is used for both utf8 and ascii
2693  *
2694  * For unicode buttons, \a buf is treated as unicode.
2695  */
2696 static bool ui_textedit_insert_buf(
2697         uiBut *but, uiHandleButtonData *data,
2698         const char *buf, int buf_len)
2699 {
2700         int len = strlen(data->str);
2701         int len_new = len - (but->selend - but->selsta) + 1;
2702         bool changed = false;
2703
2704         if (data->is_str_dynamic) {
2705                 ui_textedit_string_ensure_max_length(but, data, len_new + buf_len);
2706         }
2707
2708         if (len_new <= data->maxlen) {
2709                 char *str = data->str;
2710                 size_t step = buf_len;
2711
2712                 /* type over the current selection */
2713                 if ((but->selend - but->selsta) > 0) {
2714                         changed = ui_textedit_delete_selection(but, data);
2715                         len = strlen(str);
2716                 }
2717
2718                 if ((len + step >= data->maxlen) && (data->maxlen - (len + 1) > 0)) {
2719                         if (ui_but_is_utf8(but)) {
2720                                 /* shorten 'step' to a utf8 algined size that fits  */
2721                                 BLI_strnlen_utf8_ex(buf, data->maxlen - (len + 1), &step);
2722                         }
2723                         else {
2724                                 step = data->maxlen - (len + 1);
2725                         }
2726                 }
2727
2728                 if (step && (len + step < data->maxlen)) {
2729                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
2730                         memcpy(&str[but->pos], buf, step * sizeof(char));
2731                         but->pos += step;
2732                         changed = true;
2733                 }
2734         }
2735
2736         return changed;
2737 }
2738
2739 static bool ui_textedit_insert_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
2740 {
2741         char buf[2] = {ascii, '\0'};
2742
2743         if (ui_but_is_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
2744                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
2745                        __func__, (int)(unsigned char)ascii);
2746
2747                 return false;
2748         }
2749
2750         /* in some cases we want to allow invalid utf8 chars */
2751         return ui_textedit_insert_buf(but, data, buf, 1);
2752 }
2753
2754 static void ui_textedit_move(
2755         uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
2756         const bool select, strCursorJumpType jump)
2757 {
2758         const char *str = data->str;
2759         const int len = strlen(str);
2760         const int pos_prev = but->pos;
2761         const bool has_sel = (but->selend - but->selsta) > 0;
2762
2763         ui_but_update(but);
2764
2765         /* special case, quit selection and set cursor */
2766         if (has_sel && !select) {
2767                 if (jump == STRCUR_JUMP_ALL) {
2768                         but->selsta = but->selend = but->pos = direction ? len : 0;
2769                 }
2770                 else {
2771                         if (direction) {
2772                                 but->selsta = but->pos = but->selend;
2773                         }
2774                         else {
2775                                 but->pos = but->selend = but->selsta;
2776                         }
2777                 }
2778                 data->selextend = EXTEND_NONE;
2779         }
2780         else {
2781                 int pos_i = but->pos;
2782                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump, true);
2783                 but->pos = pos_i;
2784
2785                 if (select) {
2786                         /* existing selection */
2787                         if (has_sel) {
2788
2789                                 if (data->selextend == EXTEND_NONE) {
2790                                         data->selextend = EXTEND_RIGHT;
2791                                 }
2792
2793                                 if (direction) {
2794                                         if (data->selextend == EXTEND_RIGHT) {
2795                                                 but->selend = but->pos;
2796                                         }
2797                                         else {
2798                                                 but->selsta = but->pos;
2799                                         }
2800                                 }
2801                                 else {
2802                                         if (data->selextend == EXTEND_LEFT) {
2803                                                 but->selsta = but->pos;
2804                                         }
2805                                         else {
2806                                                 but->selend = but->pos;
2807                                         }
2808                                 }
2809
2810                                 if (but->selend < but->selsta) {
2811                                         SWAP(short, but->selsta, but->selend);
2812                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
2813                                 }
2814
2815                         } /* new selection */
2816                         else {
2817                                 if (direction) {
2818                                         data->selextend = EXTEND_RIGHT;
2819                                         but->selend = but->pos;
2820                                         but->selsta = pos_prev;
2821                                 }
2822                                 else {
2823                                         data->selextend = EXTEND_LEFT;
2824                                         but->selend = pos_prev;
2825                                         but->selsta = but->pos;
2826                                 }
2827                         }
2828                 }
2829         }
2830 }
2831
2832 static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
2833 {
2834         char *str = data->str;
2835         const int len = strlen(str);
2836
2837         bool changed = false;
2838
2839         if (jump == STRCUR_JUMP_ALL) {
2840                 if (len) changed = true;
2841                 str[0] = '\0';
2842                 but->pos = 0;
2843         }
2844         else if (direction) { /* delete */
2845                 if ((but->selend - but->selsta) > 0) {
2846                         changed = ui_textedit_delete_selection(but, data);
2847                 }
2848                 else if (but->pos >= 0 && but->pos < len) {
2849                         int pos = but->pos;
2850                         int step;
2851                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2852                         step = pos - but->pos;
2853                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - (but->pos + step));
2854                         changed = true;
2855                 }
2856         }
2857         else { /* backspace */
2858                 if (len != 0) {
2859                         if ((but->selend - but->selsta) > 0) {
2860                                 changed = ui_textedit_delete_selection(but, data);
2861                         }
2862                         else if (but->pos > 0) {
2863                                 int pos = but->pos;
2864                                 int step;
2865
2866                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump, true);
2867                                 step = but->pos - pos;
2868                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
2869                                 but->pos -= step;
2870                                 changed = true;
2871                         }
2872                 }
2873         }
2874
2875         return changed;
2876 }
2877
2878 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
2879 {
2880         char *str;
2881         int changed;
2882
2883         str = data->str;
2884
2885         if (data->searchbox)
2886                 changed = ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
2887         else
2888                 changed = but->autocomplete_func(C, str, but->autofunc_arg);
2889
2890         but->pos = strlen(str);
2891         but->selsta = but->selend = but->pos;
2892
2893         return changed;
2894 }
2895
2896 /* mode for ui_textedit_copypaste() */
2897 enum {
2898         UI_TEXTEDIT_PASTE = 1,
2899         UI_TEXTEDIT_COPY,
2900         UI_TEXTEDIT_CUT
2901 };
2902
2903 static bool ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, const int mode)
2904 {
2905         char *pbuf;
2906         bool changed = false;
2907         int buf_len;
2908         
2909         /* paste */
2910         if (mode == UI_TEXTEDIT_PASTE) {
2911                 /* extract the first line from the clipboard */
2912                 pbuf = WM_clipboard_text_get_firstline(false, &buf_len);
2913
2914                 if (pbuf) {
2915                         if (ui_but_is_utf8(but)) {
2916                                 buf_len -= BLI_utf8_invalid_strip(pbuf, buf_len);
2917                         }
2918
2919                         ui_textedit_insert_buf(but, data, pbuf, buf_len);
2920
2921                         changed = true;
2922
2923                         MEM_freeN(pbuf);
2924                 }
2925         }
2926         /* cut & copy */
2927         else if (ELEM(mode, UI_TEXTEDIT_COPY, UI_TEXTEDIT_CUT)) {
2928                 /* copy the contents to the copypaste buffer */
2929                 int sellen = but->selend - but->selsta;
2930                 char *buf = MEM_mallocN(sizeof(char) * (sellen + 1), "ui_textedit_copypaste");
2931
2932                 BLI_strncpy(buf, data->str + but->selsta, sellen + 1);
2933                 WM_clipboard_text_set(buf, 0);
2934                 MEM_freeN(buf);
2935                 
2936                 /* for cut only, delete the selection afterwards */
2937                 if (mode == UI_TEXTEDIT_CUT) {
2938                         if ((but->selend - but->selsta) > 0) {
2939                                 changed = ui_textedit_delete_selection(but, data);
2940                         }
2941                 }
2942         }
2943
2944         return changed;
2945 }
2946
2947 #ifdef WITH_INPUT_IME
2948 /* test if the translation context allows IME input - used to
2949  * avoid weird character drawing if IME inputs non-ascii chars */
2950 static bool ui_ime_is_lang_supported(void)
2951 {
2952         const char *uilng = BLT_lang_get();
2953         const bool is_lang_supported = STREQ(uilng, "zh_CN") ||
2954                                        STREQ(uilng, "zh_TW") ||
2955                                        STREQ(uilng, "ja_JP");
2956
2957         return ((U.transopts & USER_DOTRANSLATE) && is_lang_supported);
2958 }
2959
2960 /* enable ime, and set up uibut ime data */
2961 static void ui_textedit_ime_begin(wmWindow *win, uiBut *UNUSED(but))
2962 {
2963         /* XXX Is this really needed? */
2964         int x, y;
2965
2966         BLI_assert(win->ime_data == NULL);
2967
2968         /* enable IME and position to cursor, it's a trick */
2969         x = win->eventstate->x;
2970         /* flip y and move down a bit, prevent the IME panel cover the edit button */
2971         y = win->eventstate->y - 12;
2972
2973         wm_window_IME_begin(win, x, y, 0, 0, true);
2974 }
2975
2976 /* disable ime, and clear uibut ime data */
2977 static void ui_textedit_ime_end(wmWindow *win, uiBut *UNUSED(but))
2978 {
2979         wm_window_IME_end(win);
2980 }
2981
2982 void ui_but_ime_reposition(uiBut *but, int x, int y, bool complete)
2983 {
2984         BLI_assert(but->active);
2985
2986         ui_region_to_window(but->active->region, &x, &y);
2987         wm_window_IME_begin(but->active->window, x, y - 4, 0, 0, complete);
2988 }
2989
2990 wmIMEData *ui_but_ime_data_get(uiBut *but)
2991 {
2992         if (but->active && but->active->window) {
2993                 return but->active->window->ime_data;
2994         }
2995         else {
2996                 return NULL;
2997         }
2998 }
2999 #endif  /* WITH_INPUT_IME */
3000
3001 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
3002 {
3003         wmWindow *win = CTX_wm_window(C);
3004         int len;