Cursor.hpp
1 #pragma once
2 // See https://github.com/LMMS/lmms/issues/5194 for the rationale.
3 // And https://soffes.blog/aggressively-hiding-the-cursor for the hiding
4 #if defined(__APPLE__)
5 #include <ApplicationServices/ApplicationServices.h>
6 #else
7 #include <QCursor>
8 #include <QGuiApplication>
9 #endif
10 
11 #include <QGraphicsSceneMouseEvent>
12 #include <QMouseEvent>
13 #include <QPointF>
14 #include <QWidget>
15 
16 #include <score_lib_base_export.h>
17 namespace score
18 {
19 inline void setCursorPos(QPointF pos) noexcept
20 {
21 #if defined(__APPLE__)
22  CGPoint ppos;
23  ppos.x = pos.x();
24  ppos.y = pos.y();
25 
26  CGEventRef e
27  = CGEventCreateMouseEvent(nullptr, kCGEventMouseMoved, ppos, kCGMouseButtonLeft);
28  CGEventPost(kCGHIDEventTap, e);
29  CFRelease(e);
30 #else
31  QCursor::setPos(pos.toPoint());
32 #endif
33 }
34 inline void moveCursorPos(QPointF pos) noexcept
35 {
36 #if defined(__APPLE__)
37  static int i = 0;
38  i++;
39  if(i % 2)
40  {
41  // Moving a cursor is visibly an expensive operation on macos
42  // even on 3.2ghz i7 CPUs so we cull it a bit
43  return;
44  }
45  CGPoint ppos;
46  ppos.x = pos.x();
47  ppos.y = pos.y();
48 
49  CGEventRef e
50  = CGEventCreateMouseEvent(nullptr, kCGEventMouseMoved, ppos, kCGMouseButtonLeft);
51  CGEventPost(kCGHIDEventTap, e);
52  CFRelease(e);
53 #else
54  QCursor::setPos(pos.toPoint());
55 #endif
56 }
57 
58 inline QPoint globalPos(QMouseEvent* event)
59 {
60 #if defined(__APPLE__)
61  CGPoint loc;
62  {
63  CGEventRef event = CGEventCreate(nullptr);
64  loc = CGEventGetLocation(event);
65  CFRelease(event);
66  }
67  return QPoint(loc.x, loc.y);
68 #else
69  return event->globalPosition().toPoint();
70 #endif
71 }
72 
73 inline QPointF globalPos(QWidget* viewport, QGraphicsSceneMouseEvent* event)
74 {
75 #if defined(__APPLE__)
76  CGPoint loc;
77  {
78  CGEventRef event = CGEventCreate(nullptr);
79  loc = CGEventGetLocation(event);
80  CFRelease(event);
81  }
82  return QPointF(loc.x, loc.y);
83 #else
84  return viewport->mapToGlobal(QPoint{0, 0}) + event->pos();
85 #endif
86 }
87 
88 #if defined(__APPLE__)
89 SCORE_LIB_BASE_EXPORT
90 void hideCursor(bool hasCursor);
91 
92 SCORE_LIB_BASE_EXPORT
93 void showCursor();
94 #else
95 
96 inline void hideCursor(bool hasCursor)
97 {
98 #if !defined(__EMSCRIPTEN__)
99  if(QGuiApplication::overrideCursor())
100  QGuiApplication::changeOverrideCursor(QCursor(Qt::BlankCursor));
101  else
102  QGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));
103 #endif
104 }
105 inline void showCursor()
106 {
107 #if !defined(__EMSCRIPTEN__)
108  QGuiApplication::restoreOverrideCursor();
109 #endif
110 }
111 #endif
112 }
Base toolkit upon which the software is built.
Definition: Application.cpp:90