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