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