Compare commits

...

140 Commits

Author SHA1 Message Date
oguzhankoral 9e278042c8 WIP 2024-07-18 12:17:58 +02:00
Oğuzhan Koral f20b26045c Align collections and proxies (#342) 2024-07-18 01:10:03 +02:00
Oğuzhan Koral 4bcbc5131b Fix missing objects in definition proxy (#341) 2024-07-16 16:21:47 +02:00
Oğuzhan Koral eeea2d7c8d Grouped meshes by layer and material (#339)
* POC grouped meshes for perf

* Better group mesh

* Add doc fix minor

* Consider back material for meshes

* Remove unused grouped meshes functions

* Remove unnecessary line
2024-07-16 12:57:19 +02:00
Oğuzhan Koral 68e9468294 Fix progress update and some performance (#338)
* Fix send conversion status

* Do not add non-orphan edges to flat atomic objects (~3x performance gain)
2024-07-10 18:55:18 +03:00
Oğuzhan Koral 694da73b77 Fix(blocks): update max depth of children (#337)
* Temp fix

* Update max depth of children
2024-07-09 13:59:16 +03:00
Oğuzhan Koral 15657bf0ec Feat (dui3): New blocks (#336)
* Add proxy objects

* Rename materials and definitions

* Add DefinitionManager

* Fix minor

* Tweak in converter

* Fix units

* Converter v2

* Split converter and converter_v2

* Sort arguments for converters

* Change inner terminology to FE2 for native converter v2

* Simplify arguments

* Remove one click send

* Convert definition proxies in advance then instance proxies

* Yey

* Accept uppercase Units too
2024-06-27 23:09:46 +03:00
oguzhankoral 78c6898ff0 Fix baked object ids 2024-06-05 21:47:09 +03:00
oguzhankoral 836e97a57c Flat stack trace from array to string 2024-06-05 15:11:33 +03:00
oguzhankoral 7f708108f2 Pass error message into hash to serialize 2024-06-05 15:02:53 +03:00
oguzhankoral 2d3e282150 Remove receive result -store only baked object ids 2024-06-05 14:44:01 +03:00
oguzhankoral 75b933ef0a Add conversion_result class and align for send receive 2024-06-05 14:33:16 +03:00
oguzhankoral c19799f081 Send conversion results 2024-06-03 10:37:03 +03:00
oguzhankoral 848ed922b5 Merge coplanar faces from after_get_objects 2024-05-22 11:13:37 +03:00
oguzhankoral 16e96b69a4 Set active path always to model before send 2024-05-13 18:24:36 +03:00
oguzhankoral fbdd7ee7b6 Include parents too onChangeEntity 2024-05-13 18:13:37 +03:00
oguzhankoral d3df5fceec Handle entity paths elegantly 2024-05-13 14:15:43 +03:00
oguzhankoral 948925d156 Ignore cache for grouped meshes since it breaks the object structure 2024-05-13 12:35:26 +03:00
oguzhankoral 7ab6b1b167 Do not group meshes with object referenced meshes 2024-05-13 12:23:25 +03:00
oguzhankoral ca3a109bc8 Fix non-selected update infinity json error 2024-05-13 11:11:22 +03:00
oguzhankoral ebe9551e72 Add 2024 support for DUI3 Mac 2024-05-10 10:46:31 +03:00
oguzhankoral d2836189c3 Add 2024 support for DUI3 2024-05-08 19:17:06 +03:00
oguzhankoral 3703963ec8 Merge branch 'oguzhan/worker-thread-poc' into oguzhan/dui3 2024-05-08 14:35:11 +03:00
oguzhankoral 02ca8e3a59 Do instance message send via worker 2024-05-08 02:34:32 +03:00
oguzhankoral 7c73658fa5 Remove TT dependency 2024-05-08 02:20:40 +03:00
oguzhankoral e03b448618 Enable progress bar while converting from selected entities 2024-05-08 01:33:19 +03:00
oguzhankoral c8d635752b Implement instant_message_sender over worker 2024-05-08 00:59:09 +03:00
oguzhankoral df9a5600d9 Fallback to ModelCollection always if collectionType not set 2024-05-07 23:35:17 +03:00
oguzhankoral dd730ea517 Fix typo 2024-05-07 23:18:46 +03:00
oguzhankoral 5bbfe1be59 Disable old UI button 2024-05-07 21:50:23 +03:00
oguzhankoral dd04bd8792 Rename DUI3 with New UI 2024-05-07 14:48:04 +03:00
oguzhankoral 20bc1f41f0 Fix typo on clearing cache on document switch 2024-05-07 14:25:24 +03:00
oguzhankoral 9e838734c0 Resize speckle icons
Co-authored-by: name <mucahitbgoker@gmail.com>
2024-05-07 14:18:01 +03:00
oguzhankoral 17aeca5e70 Clear cache on document switch 2024-05-07 13:46:02 +03:00
Mucahit Bilal GOKER 98852d8c22 Updated connector icons (#329) 2024-05-07 13:38:02 +03:00
oguzhankoral 674d9cd37d Track also session based ids
This was needed because of onElementRemoved only provides `entityID` instead `persistent_id`......
2024-05-07 12:55:55 +03:00
oguzhankoral c35f9c22ae Extract run expiration checks 2024-05-07 11:01:24 +03:00
oguzhankoral e5f861c0dc Invalidate sub elements of component if created 2024-05-07 10:39:22 +03:00
oguzhankoral 7a31143ef4 Highlight and remember received objects 2024-05-06 15:46:41 +03:00
oguzhankoral 9daa0e4059 Do not send if nothing selected 2024-05-06 12:40:54 +03:00
oguzhankoral eaedeb4f8b Implement getConnectorVersion 2024-05-06 12:13:10 +03:00
oguzhankoral bd2f1d2777 Add missing latest_version_id and has_dismissed_update_warning for receive card 2024-04-30 15:29:30 +03:00
oguzhankoral 52e43bac2d Make elements backward compatible 2024-04-29 10:11:23 +03:00
oguzhankoral daef503970 Wrap DUI3 receive into sketchup operation 2024-04-29 10:10:53 +03:00
oguzhankoral 4d0ba3cd13 Remove placeholder everything and tag send filters 2024-04-29 09:30:34 +03:00
oguzhankoral bd111a2106 Lowercase the app name 2024-04-22 11:40:39 +03:00
oguzhankoral 22daade5d2 Add EntityObserver for Edge and Vertex change detection 2024-03-25 14:24:17 +03:00
oguzhankoral a39d72a59d Change detections for entities 2024-03-25 14:24:06 +03:00
oguzhankoral 3a2e523589 Do not iterate closure table if nil 2024-03-22 12:26:25 +03:00
oguzhankoral 8bd27c6ad1 ObjectReference for previously converted objects 2024-03-21 20:13:11 +03:00
oguzhankoral 4c20cf67c8 Serializer adjustments for ObjectReference
- Previous state and sketchup entity pollution on serializer cleared up
2024-03-21 14:13:01 +03:00
oguzhankoral 337da3d523 Add option for netlify ui url 2024-03-19 14:55:41 +03:00
oguzhankoral 3050803e68 Send according to filter and expiration 2024-03-19 14:28:30 +03:00
oguzhankoral beb803fc63 Read/write cards correctly 2024-03-19 14:28:29 +03:00
oguzhankoral b056bcae2c Remove unnecessary sourceApplication 2024-03-19 14:28:29 +03:00
oguzhankoral 6a2c297640 Fix renames 2024-03-19 14:28:29 +03:00
oguzhankoral 8b3127eda4 Fix selection 2024-03-19 14:28:29 +03:00
oguzhankoral b63d51ab1d Align boilerplate config 2024-03-19 14:28:29 +03:00
oguzhankoral 3b2dfd27d6 Fix changed property for modelCardId 2024-03-19 14:28:29 +03:00
oguzhankoral b8753195df Solve post-conflicts with dev 2024-03-19 14:28:29 +03:00
oguzhankoral e76eb113a5 Zoom selection for highlight 2024-03-19 14:28:29 +03:00
oguzhankoral d285e10565 Update sqlite3 submodule hash ref 2024-03-19 14:28:29 +03:00
oguzhankoral 66803f9036 Highlight model for send cards 2024-03-19 14:28:29 +03:00
oguzhankoral d7cff48374 Remove cards from model 2024-03-19 14:28:29 +03:00
oguzhankoral d66ed0566b Add action name to error message for commands 2024-03-19 14:28:29 +03:00
oguzhankoral fde2b3bf0f First successful receive 2024-03-19 14:28:29 +03:00
oguzhankoral dcc8270cc6 Send progressbar with Sketchup.status_text
Thanks to library of thomthom
2024-03-19 14:28:29 +03:00
oguzhankoral 23b6ca7552 Send model card id via sendViaBrowserArgs 2024-03-19 14:28:29 +03:00
oguzhankoral 437173e6a4 Get source app version via base bindings 2024-03-19 14:28:29 +03:00
oguzhankoral 1274facbed Send message from sender card 2024-03-19 14:28:29 +03:00
oguzhankoral 180fc2ca59 Correct send data 2024-03-19 14:28:28 +03:00
oguzhankoral 187cf8f55e Real send via DUI3 2024-03-19 14:28:28 +03:00
oguzhankoral dd8868b2a2 Trigger sendersExpired when objects modified 2024-03-19 14:28:28 +03:00
oguzhankoral 921e8ea1a8 Use AddModel action for updateModel command 2024-03-19 14:28:28 +03:00
oguzhankoral 54e8782e12 Place binding classes into folder 2024-03-19 14:28:28 +03:00
oguzhankoral 9e690dd304 Enable error catch for command 2024-03-19 14:28:28 +03:00
oguzhankoral 373b42041b Update model card 2024-03-19 14:28:28 +03:00
oguzhankoral 30ead47fb9 Add type discriminator 2024-03-19 14:28:28 +03:00
oguzhankoral 2dc7206f17 Reorganize send bindings 2024-03-19 14:28:28 +03:00
oguzhankoral ab7594bd23 Split account binding from base 2024-03-19 14:28:28 +03:00
oguzhankoral 710a22aea7 Align with Dim's works 2024-03-19 14:28:28 +03:00
oguzhankoral 2c7c801efc WIP: selection bindings - add cards to model 2024-03-19 14:28:28 +03:00
oguzhankoral 41ebe058e7 WIP: filters 2024-03-19 14:28:28 +03:00
oguzhankoral 288c71b3e0 Convert tag colors to hex 2024-03-19 14:28:28 +03:00
oguzhankoral d7a8afcb31 Get default filters 2024-03-19 14:28:28 +03:00
oguzhankoral a1d120ee22 Get model state and send filter for sketchup 2024-03-19 14:28:28 +03:00
oguzhankoral b58d6d0d82 WIP: connector configs 2024-03-19 14:28:28 +03:00
oguzhankoral 5ab65391ca Implement config_binding 2024-03-19 14:28:28 +03:00
oguzhankoral 2b40d58996 Introduce ruby traverse_and_construct 2024-03-19 14:28:28 +03:00
oguzhankoral 96129388ec Send-Receive operations test via ruby 2024-03-19 14:28:25 +03:00
oguzhankoral 6f6058a2d1 Remove test bridge.js 2024-03-19 14:27:56 +03:00
oguzhankoral 063ef91613 Unit test for send operation 2024-03-19 14:27:56 +03:00
oguzhankoral 5233072099 Enable collect preferences 2024-03-19 14:27:56 +03:00
oguzhankoral cd063b0e8a Emit only documentChanged instead of passing data 2024-03-19 14:27:56 +03:00
oguzhankoral 719d796e20 Rename views to bindings 2024-03-19 14:27:56 +03:00
oguzhankoral 9767bf5261 Report errors to UI 2024-03-19 14:27:56 +03:00
oguzhankoral a9998bf12d Resolve triggerEvent 2024-03-19 14:27:56 +03:00
oguzhankoral 2b7dc899e1 Implement test bindings 2024-03-19 14:27:56 +03:00
oguzhankoral cbc3f51d4c Create random sketchup binding 2024-03-19 14:27:56 +03:00
oguzhankoral ff1c8c1bfe Implement on_document_changed action 2024-03-19 14:27:56 +03:00
oguzhankoral 6d4222bb1a Add command for get document info 2024-03-19 14:27:56 +03:00
oguzhankoral 7692a6f258 Remove get_commands action and command 2024-03-19 14:27:56 +03:00
oguzhankoral ed8e6b00c6 Apply same dialog-view relationship to legacy UI 2024-03-19 14:27:56 +03:00
oguzhankoral 85db9570dd Control views via dialog 2024-03-19 14:27:56 +03:00
oguzhankoral be174b9cce Remove unnecssary init from view 2024-03-19 14:27:56 +03:00
oguzhankoral f0099090b4 Collect command names from related view for SketchupBridge 2024-03-19 14:27:56 +03:00
oguzhankoral b72bdfcbf0 Pass view to commands 2024-03-19 14:27:53 +03:00
oguzhankoral e1f5addddc Send messages to correct view/binding 2024-03-19 14:23:06 +03:00
oguzhankoral 87d3145317 Solve missing resolve_id arguments for commands and actions 2024-03-19 14:23:06 +03:00
oguzhankoral 84fc89cbbe Run legacy and dui3 at the same time 2024-03-19 14:23:06 +03:00
oguzhankoral fbbddd8365 Pass resolve id from arguments 2024-03-19 14:23:06 +03:00
oguzhankoral dcfb787563 Replace Bridge with inhouse resolve_id solution 2024-03-19 14:23:06 +03:00
oguzhankoral 6822b2db9b Pass serialized accounts data as json object 2024-03-19 14:23:06 +03:00
oguzhankoral d89b3772de Pass correct request id for getAccounts 2024-03-19 14:23:06 +03:00
oguzhankoral e4a4eb0455 Request id temp hack 2024-03-19 14:23:06 +03:00
oguzhankoral 759efa7da3 Add get commands 2024-03-19 14:23:06 +03:00
oguzhankoral bf1c271784 Add bridge sample 2024-03-19 14:23:06 +03:00
oguzhankoral 9754893181 Check correct dui3 id ui controller 2024-03-19 14:23:06 +03:00
oguzhankoral 5b05182a1c Add new dialog for dui3 2024-03-19 14:23:00 +03:00
Alan Rynne 7de08d9f24 fix: Use correct digicert context + pass fingerprint to ISS compiler (#328)
* fix: Use correct digicert context + pass fingerprint to ISS compiler

* Update config.yml

* Update config.yml

---------

Co-authored-by: Jedd Morgan <45512892+JR-Morgan@users.noreply.github.com>
2024-03-14 11:27:45 +00:00
Oğuzhan Koral d047f5e6d2 Chore (URL): CNX-9018 Do not add model from multi model urls
- warn user and return
- otherwise add
2024-02-29 15:13:44 +03:00
Oğuzhan Koral 71071f817c Make FE2 terminology default (#326) 2024-02-27 17:09:38 +03:00
Oğuzhan Koral c7c864b8c0 Feat (CI): Update CI for digicert (#325)
* Update CI for digicert

* Checkout speckle-sharp-ci-tools branch if exist
2024-02-27 12:36:25 +03:00
Oğuzhan Koral 67d4862f6b Fix (Mapper): CNX-9027 mapped edges don't send at all (#324)
* Separate native revit object definitions

* Add types for native revit objects

* Pass speckle_state to line conversion

* Remove mapper functions from model collections

* Use dictionary pattern matching for mapping conversions

* Remove unnecessary argument from Mapper.to_speckle
2024-02-21 16:59:40 +03:00
Oğuzhan Koral 6a16327c30 Fix (Cache): CNX-8976 bug on initialization on clear setup (#323)
* Call sketchup functions before mount

* Change default to app.speckle.systems

* Use account id instead uuid to get selected account before
2024-02-20 23:54:15 +03:00
Oğuzhan Koral 060b1b8f41 Fix (Attributes): Fix typos 2024-02-15 16:43:32 +03:00
Oğuzhan Koral da2e228293 Fix (FE2): CNX-8877 bug access error by fe2 model url (#321)
* Disable reload

* Enrich selected account info and fix same user id issue

* Trigger sketchup only saved stream not exists

* Fix activeAccount

* Increase number of branches limit to 100

* Check regex match
2024-02-13 16:36:35 +03:00
Oğuzhan Koral ab7397bf55 Feat (FE2): CNX-8702 fe2 urls (#320)
* Recreate ApolloProvider whenever account switches

- It is a force-push of reload page whenever user switches account. It doesn't hurt

* Fix FE2 urls and streamWrapper flag argument
2024-02-03 02:36:41 +03:00
Oğuzhan Koral f79547f781 Reset UI location to center of SketchUp (#319) 2024-01-31 23:00:46 +03:00
Oğuzhan Koral 2152f1c90e Feat (Mapper): CNX-8309 Family instances (#318)
* Implement New Revit Family option

* Filter family types for 'Family Instance'

* Adjust available mapping methods according to selection

* Set hard coded categories just once and source families when source set/updated

* Implement family instance mapping

* Pass group selection info if only group selected

* Exclude definitions from conversion escape

- Previously we were using definition mappings only for direct shape conversions but now they can live in instances

* Add direct shape option to components back

* Calculate rotation of family instance

* Fix transformation matrix

* Use insertion point for instances

* Set inputs for mapped definition
2024-01-08 18:40:55 +03:00
Oğuzhan Koral 503fb4d246 Feat (GIS): support line element 2023-12-01 01:46:53 +03:00
oguzhankoral 2befefa752 Extract utils for line and polygon element 2023-11-30 15:07:31 +03:00
oguzhankoral 85e64c5076 Add line element support 2023-11-30 00:36:47 +03:00
Oğuzhan Koral 60523dc994 Fix (Collections): Support gis collections and none unit 2023-11-29 16:06:58 +03:00
oguzhankoral 6d780bf350 Rename GisLayerCollection as generic 2023-11-29 16:06:37 +03:00
oguzhankoral eec02a1f84 Support none unit 2023-11-29 15:58:26 +03:00
oguzhankoral ace2fe6fe3 WIP: Convert from 'meters' to 'm' 2023-11-29 13:26:53 +03:00
oguzhankoral 188794af8d Add support for vector layer 2023-11-29 13:26:53 +03:00
Oğuzhan Koral 92a941a944 Fix (Instancing): correct id of definition for speckle entity 2023-11-29 13:25:51 +03:00
oguzhankoral 0e1ddf2b11 Tweak definition speckle entity checks 2023-11-29 13:15:07 +03:00
210 changed files with 6447 additions and 766 deletions
+47 -34
View File
@@ -26,21 +26,17 @@ jobs:
build-connector: # Reusable job for basic connectors
executor:
name: win/default # comes with python 3.7.3
shell: cmd.exe
shell: powershell.exe
parameters:
slug:
type: string
default: ""
environment:
SSM: 'C:\Program Files\DigiCert\DigiCert One Signing Manager Tools'
steps:
- checkout
- attach_workspace:
at: ./
- run:
name: Create Innosetup signing cert
shell: powershell.exe
command: |
echo $env:PFX_B64 > "speckle-sharp-ci-tools\SignTool\AEC Systems Ltd.txt"
certutil -decode "speckle-sharp-ci-tools\SignTool\AEC Systems Ltd.txt" "speckle-sharp-ci-tools\SignTool\AEC Systems Ltd.pfx"
- run:
name: Set Environment Variable
shell: powershell.exe
@@ -52,25 +48,36 @@ jobs:
python patch_version.py $semver
environment:
WORKFLOW_NUM: << pipeline.number >>
- run:
name: Build Installer
command: speckle-sharp-ci-tools\InnoSetup\ISCC.exe speckle-sharp-ci-tools\sketchup.iss /Sbyparam=$p
shell: cmd.exe #does not work in powershell
#- run:
# name: Patch
# shell: powershell.exe
# command:
# | # If no tag, use 0.0.0.1 and don't make any YML (for testing only!)
# $tag = if([string]::IsNullOrEmpty($env:CIRCLE_TAG)) { "0.0.0" } else { $env:CIRCLE_TAG }
# $semver = if($tag.Contains('/')) {$tag.Split("/")[1] } else { $tag }
# $ver = if($semver.Contains('-')) {$semver.Split("-")[0] } else { $semver }
# $channel = if($semver.Contains('-')) {$semver.Split("-")[1] } else { "latest" }
# $version = "$($ver).$($env:CIRCLE_BUILD_NUM)"
# New-Item -Force "speckle-sharp-ci-tools/Installers/sketchup/$channel.yml" -ItemType File -Value "version: $semver"
# echo $version
# python patch_version.py $semver
# speckle-sharp-ci-tools\InnoSetup\ISCC.exe speckle-sharp-ci-tools\sketchup.iss
- unless: # Build installers unsigned on non-tagged builds
condition: << pipeline.git.tag >>
steps:
- run:
name: Build Installer
command: speckle-sharp-ci-tools\InnoSetup\ISCC.exe speckle-sharp-ci-tools\sketchup.iss /Sbyparam=$p
shell: cmd.exe # does not work in powershell
- when: # Setup certificates and build installers signed for tagged builds
condition: << pipeline.git.tag >>
steps:
- run:
name: "Digicert Signing Manager Setup"
command: |
cd C:\
curl.exe -X GET https://one.digicert.com/signingmanager/api-ui/v1/releases/smtools-windows-x64.msi/download -H "x-api-key:$env:SM_API_KEY" -o smtools-windows-x64.msi
msiexec.exe /i smtools-windows-x64.msi /quiet /qn | Wait-Process
- run:
name: "Create Auth & OV Signing Cert"
command: |
cd C:\
echo $env:SM_CLIENT_CERT_FILE_B64 > certificate.txt
certutil -decode certificate.txt certificate.p12
- run:
name: "Sync Certs"
command: |
& $env:SSM\smksp_cert_sync.exe
- run:
name: "Build Installer"
command: speckle-sharp-ci-tools\InnoSetup\ISCC.exe speckle-sharp-ci-tools\sketchup.iss /Sbyparam=$p /DSIGN_INSTALLER /DCODE_SIGNING_CERT_FINGERPRINT=%SM_CODE_SIGNING_CERT_SHA1_HASH%
shell: cmd.exe
- persist_to_workspace:
root: ./
paths:
@@ -135,8 +142,8 @@ jobs:
- run:
name: Copy files to installer
command: |
mkdir -p speckle-sharp-ci-tools/Mac/<< parameters.installername >>/.installationFiles/
cp << parameters.slug >>-mac.zip speckle-sharp-ci-tools/Mac/<<parameters.installername>>/.installationFiles
mkdir -p speckle-sharp-ci-tools/Mac/<< parameters.installername >>/.installationFiles/
cp << parameters.slug >>-mac.zip speckle-sharp-ci-tools/Mac/<<parameters.installername>>/.installationFiles
# Create installer
- run:
name: Exit if External PR
@@ -168,7 +175,7 @@ jobs:
root: ./
paths:
- speckle-sharp-ci-tools/Installers
get-ci-tools: # Clones our ci tools and persists them to the workspace
docker:
- image: cimg/base:2021.01
@@ -184,10 +191,16 @@ jobs:
- run:
name: Clone
command: git clone git@github.com:specklesystems/speckle-sharp-ci-tools.git speckle-sharp-ci-tools
- persist_to_workspace:
root: ./
paths:
- speckle-sharp-ci-tools
- run:
name: Checkout branch
command: |
cd speckle-sharp-ci-tools
if [ -z "$CIRCLE_TAG" ]
then
git checkout ${CIRCLE_BRANCH} || git checkout main
else
git checkout ${CIRCLE_TAG} || git checkout main
fi
- persist_to_workspace:
root: ./
paths:
@@ -238,7 +251,7 @@ workflows:
filters:
tags:
only: /.*/
context: innosetup
context: digicert-keylocker
- build-connector-mac:
slug: sketchup
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@@ -7,6 +7,7 @@ require_relative '../constants/path_constants'
module SpeckleConnector
# Accounts to communicate with models on user's account.
module Accounts
# Load accounts from user's app data.
def self.load_accounts
db_path = SPECKLE_ACCOUNTS_DB_PATH
unless File.exist?(db_path)
@@ -23,9 +24,21 @@ module SpeckleConnector
rows.map { |row| JSON.parse(row[1]) }
end
def self.get_account_by_id(id)
accounts = load_accounts
accounts.select { |acc| acc['id'] == id }[0]
end
# Default account on the user computer.
def self.default_account
accounts = load_accounts
accounts.select { |acc| acc['isDefault'] }[0] || accounts[0]
end
# Try to get local server account for debug/test purposes.
def self.try_get_local_server_account
accounts = load_accounts
accounts.select { |acc| acc['serverInfo']['url'].include?('localhost') }[0] || nil
end
end
end
@@ -15,7 +15,7 @@ module SpeckleConnector
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def update_state(state)
state = DeactivateDiffing.update_state(state, {})
state = DeactivateDiffing.update_state(state, nil, {})
puts "Diffing activated for #{@stream_id}"
speckle_entities = state.speckle_state.speckle_entities
invalid_speckle_entities = speckle_entities.select do |_id, entity|
@@ -0,0 +1,28 @@
# frozen_string_literal: true
require_relative 'add_send_model_card'
require_relative 'add_receive_model_card'
require_relative '../action'
require_relative '../../cards/send_card'
require_relative '../../cards/receive_card'
require_relative '../../filters/send/everything_filter'
require_relative '../../filters/send/selection_filter'
require_relative '../../filters/send_filters'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to add send card.
class AddModel < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data)
if data['typeDiscriminator'] == 'SenderModelCard'
Actions::AddSendModelCard.update_state(state, resolve_id, data)
else
Actions::AddReceiveModelCard.update_state(state, resolve_id, data)
end
end
end
end
end
@@ -0,0 +1,44 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../cards/send_card'
require_relative '../../cards/receive_card'
require_relative '../../filters/send/everything_filter'
require_relative '../../filters/send/selection_filter'
require_relative '../../filters/send_filters'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to add receive model card.
class AddReceiveModelCard < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data)
model_card_id = data['modelCardId']
account_id = data['accountId']
project_id = data['projectId']
model_id = data['modelId']
project_name = data['projectName']
model_name = data['modelName']
expired = data['expired']
selected_version_id = data['selectedVersionId']
latest_version_id = data['latestVersionId']
has_dismissed_update_warning = data['hasDismissedUpdateWarning']
baked_object_ids = data['bakedObjectIds'].nil? ? nil : data['bakedObjectIds'].values
receive_card = Cards::ReceiveCard.new(model_card_id, account_id,
project_id, model_id,
project_name, model_name,
selected_version_id, latest_version_id,
has_dismissed_update_warning, expired, baked_object_ids)
SketchupModel::Dictionary::ModelCardDictionaryHandler
.save_receive_card_to_model(receive_card, state.sketchup_state.sketchup_model)
new_speckle_state = state.speckle_state.with_receive_card(receive_card)
state = state.with_speckle_state(new_speckle_state)
js_script = "baseBinding.receiveResponse('#{resolve_id}')"
return state.with_add_queue_js_command('addReceiveCard', js_script)
end
end
end
end
@@ -0,0 +1,43 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../cards/send_card'
require_relative '../../cards/receive_card'
require_relative '../../filters/send/everything_filter'
require_relative '../../filters/send/selection_filter'
require_relative '../../filters/send_filters'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to add send model card.
class AddSendModelCard < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data)
send_filter = Filters::SendFilters.get_filter_from_ui_data(data['sendFilter'])
# Init card and add to the state
send_card = Cards::SendCard.new(
data['modelCardId'],
data['accountId'],
data['projectId'],
data['projectName'],
data['modelId'],
data['modelName'],
data['latestCreatedVersionId'],
send_filter,
{}
)
SketchupModel::Dictionary::ModelCardDictionaryHandler
.save_send_card_to_model(send_card, state.sketchup_state.sketchup_model)
new_speckle_state = state.speckle_state.with_send_card(send_card)
state = state.with_speckle_state(new_speckle_state)
# Resolve promise
js_script = "baseBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('addSendCard', js_script)
end
end
end
end
@@ -0,0 +1,17 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Get connector version.
class GetConnectorVersion < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
js_command = "baseBinding.receiveResponse('#{resolve_id}', '#{CONNECTOR_VERSION}')"
state.with_add_queue_js_command('getConnectorVersion', js_command)
end
end
end
end
@@ -0,0 +1,80 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../filters/send_filters'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Gets document state.
class GetDocumentState < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
send_cards_hash = SketchupModel::Dictionary::ModelCardDictionaryHandler
.get_send_cards_from_dict(state.sketchup_state.sketchup_model)
# TODO: CONVERTER_V2: Extract into new actions
send_cards = send_cards_hash.collect do |id, card|
filter = Filters::SendFilters.get_filter_from_document(card['sendFilter'])
send_card = Cards::SendCard.new(
id,
card['account_id'],
card['project_id'],
card['project_name'],
card['model_id'],
card['model_name'],
card['latest_created_version_id'],
filter,
{}
)
new_speckle_state = state.speckle_state.with_send_card(send_card)
state = state.with_speckle_state(new_speckle_state)
{
modelCardId: send_card.model_card_id,
accountId: send_card.account_id,
projectId: send_card.project_id,
modelId: send_card.model_id,
sendFilter: send_card.send_filter,
latestCreatedVersionId: send_card.latest_created_version_id,
typeDiscriminator: send_card.type_discriminator
}
end
receive_cards_hash = SketchupModel::Dictionary::ModelCardDictionaryHandler
.get_receive_cards_from_dict(state.sketchup_state.sketchup_model)
# TODO: CONVERTER_V2: Extract into new actions
receive_cards = receive_cards_hash.collect do |id, card|
receive_card = Cards::ReceiveCard.new(id, card['account_id'], card['project_id'], card['model_id'],
card['project_name'], card['model_name'], card['selected_version_id'],
card['latest_version_id'], card['has_dismissed_update_warning'],
card['expired'], card['baked_object_ids'])
new_speckle_state = state.speckle_state.with_receive_card(receive_card)
state = state.with_speckle_state(new_speckle_state)
{
modelCardId: receive_card.model_card_id,
accountId: receive_card.account_id,
projectId: receive_card.project_id,
modelId: receive_card.model_id,
projectName: receive_card.project_name,
modelName: receive_card.model_name,
selectedVersionId: receive_card.selected_version_id,
latestVersionId: receive_card.latest_version_id,
hasDismissedUpdateWarning: receive_card.has_dismissed_update_warning,
expired: receive_card.expired,
bakedObjectIds: receive_card.baked_object_ids,
typeDiscriminator: receive_card.type_discriminator
}
end
model_state = { models: send_cards + receive_cards }
js_script = "baseBinding.receiveResponse('#{resolve_id}', #{model_state.to_json})"
state.with_add_queue_js_command('getDocumentState', js_script)
end
end
end
end
@@ -0,0 +1,19 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../filters/send_filters'
module SpeckleConnector
module Actions
# Action to get send filter.
class GetSendFilters < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
default_filters = Filters::SendFilters.get_default(state.sketchup_state.sketchup_model)
js_script = "sendBinding.receiveResponse('#{resolve_id}', #{default_filters.to_json})"
state.with_add_queue_js_command('getSendFilter', js_script)
end
end
end
end
@@ -0,0 +1,17 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Get source app name.
class GetSourceAppName < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
js_command = "baseBinding.receiveResponse('#{resolve_id}', 'sketchup')"
state.with_add_queue_js_command('getSourceAppName', js_command)
end
end
end
end
@@ -0,0 +1,17 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Get source app version.
class GetSourceAppVersion < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
js_command = "baseBinding.receiveResponse('#{resolve_id}', #{SKETCHUP_VERSION})"
state.with_add_queue_js_command('getSourceAppVersion', js_command)
end
end
end
end
@@ -0,0 +1,31 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/query/entity'
module SpeckleConnector
module Actions
# Action to add send card.
class HighlightModel < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, model_card_id)
receiver_card = state.speckle_state.receive_cards[model_card_id]
sender_card = state.speckle_state.send_cards[model_card_id]
card = receiver_card || sender_card
objects_to_highlight = if card.type_discriminator == 'ReceiverModelCard'
state.speckle_state.receive_cards[model_card_id].baked_object_ids
else
state.speckle_state.send_cards[model_card_id].send_filter.selected_object_ids
end
SketchupModel::Utils::ViewUtils.highlight_entities(state.sketchup_state.sketchup_model, objects_to_highlight)
# Resolve promise
js_script = "baseBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('highlightModel', js_script)
end
end
end
end
@@ -0,0 +1,20 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/query/entity'
require_relative '../../sketchup_model/utils/view_utils'
module SpeckleConnector
module Actions
# Action to add send card.
class HighlightObjects < Action
def self.update_state(state, resolve_id, object_ids)
SketchupModel::Utils::ViewUtils.highlight_entities(state.sketchup_state.sketchup_model, object_ids)
# Resolve promise
js_script = "baseBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('highlightObjects', js_script)
end
end
end
end
@@ -0,0 +1,31 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../cards/send_card'
require_relative '../../cards/receive_card'
require_relative '../../filters/send/everything_filter'
require_relative '../../filters/send/selection_filter'
require_relative '../../filters/send_filters'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to remove send card.
class RemoveModel < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data)
SketchupModel::Dictionary::ModelCardDictionaryHandler.remove_card_dict(state.sketchup_state.sketchup_model, data)
new_speckle_state = if data['typeDiscriminator'] == 'ReceiverModelCard'
state.speckle_state.without_receive_card(data['id'])
else
state.speckle_state.without_send_card(data['id'])
end
state = state.with_speckle_state(new_speckle_state)
# Resolve promise
js_script = "baseBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('removeModel', js_script)
end
end
end
end
@@ -0,0 +1,20 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to update send filter.
class UpdateSendFilter < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data, value)
SketchupModel::Dictionary::ModelCardDictionaryHandler.update_filter(state.sketchup_state.sketchup_model, data, value)
js_script = "sendBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('updateSendFilter', js_script)
end
end
end
end
@@ -9,7 +9,7 @@ module SpeckleConnector
class ClearMapperSource < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
new_speckle_state = state.speckle_state.with_removed_mapper_source
erase_levels(state)
state.with_speckle_state(new_speckle_state)
@@ -11,7 +11,7 @@ module SpeckleConnector
class ClearMappingsFromTable < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, data)
def self.update_state(state, _resolve_id, data)
# Flat entities to clear mappings
flat_entities = SketchupModel::Query::Entity.flat_entities(state.sketchup_state.sketchup_model.entities)
@@ -10,7 +10,7 @@ module SpeckleConnector
class CollectPreferences < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
state.with_add_queue('collectPreferences', state.user_state.preferences.to_json, [])
end
end
@@ -8,7 +8,7 @@ module SpeckleConnector
class CollectVersions < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
versions = {
sketchup: Sketchup.version.to_i,
speckle: SpeckleConnector::CONNECTOR_VERSION
@@ -0,0 +1,29 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Action to get config.
class GetConfig < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
# Previously it was stored in user state
# config = state.user_state.preferences.to_json
config = {
global: {
},
connectors: {
sketchup: {
darkTheme: state.user_state.user_preferences[:dark_theme]
}
}
}
js_script = "configBinding.receiveResponse('#{resolve_id}', #{config.to_json})"
state.with_add_queue_js_command('getConfig', js_script)
end
end
end
end
@@ -0,0 +1,26 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../user_preferences_updated'
module SpeckleConnector
module Actions
# Action to update config.
class UpdateConfig < Action
KEY_VALUES = {
'darkTheme' => 'dark_theme'
}.freeze
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, config)
config.each do |key, value|
state = Actions::UserPreferencesUpdated.new('configSketchup', KEY_VALUES[key], value).update_state(state)
end
js_script = "configBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('updateConfig', js_script)
end
end
end
end
@@ -8,7 +8,7 @@ module SpeckleConnector
class DeactivateDiffing < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
puts 'Diffing deactivated!'
speckle_entities = state.speckle_state.speckle_entities
diffing_activated_speckle_entities = speckle_entities.reject do |_id, entity|
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require_relative 'event_action'
require_relative 'on_document_changed'
require_relative '../load_sketchup_model'
require_relative '../collect_preferences'
@@ -25,7 +26,8 @@ module SpeckleConnector
# Action to let UI to render itself with new preferences state
# TODO: Later UI should be updated if any stream is invalid after
# we collected speckle_entities appropriately
CollectPreferences.update_state(new_state, {})
new_state = CollectPreferences.update_state(new_state, nil, {})
OnDocumentChanged.update_state(new_state)
end
end
@@ -1,14 +1,17 @@
# frozen_string_literal: true
require_relative 'event_action'
require_relative '../../actions/send_actions/send_card_expiration_check'
require_relative '../../sketchup_model/utils/face_utils'
require_relative '../../constants/dict_constants'
require_relative '../../sketchup_model/query/path'
module SpeckleConnector
module Actions
module Events
# Event actions related to entities.
class EntitiesEventAction < EventAction
PATH = SketchupModel::Query::Path
# Event action when element added.
class OnElementAdded
# @param state [States::State] the current state of the SpeckleConnector Application
@@ -16,33 +19,91 @@ module SpeckleConnector
modified_entities = event_data.to_a.collect { |e| e[1] }
# do not copy speckle base object specific attributes, because they are entity specific
modified_entities.each { |entity| entity.delete_attribute(SPECKLE_BASE_OBJECT) }
# All parent ids on current active path
parent_ids = PATH.parents_with_definitions(state.sketchup_state.sketchup_model).collect(&:persistent_id)
# All instances that changed potentially because of potential definition update
path_instance_ids = PATH.instances(state.sketchup_state.sketchup_model).collect(&:persistent_id)
wrapped_entity_ids = wrapped_entity_ids(modified_entities)
ids_to_check = parent_ids + wrapped_entity_ids + path_instance_ids
state = EntitiesEventAction.run_expiration_checks(state, ids_to_check) if ids_to_check.any?
attach_edge_entity_observer(modified_entities.grep(Sketchup::Edge), state.speckle_state.observers[ENTITY_OBSERVER])
state
end
def self.wrapped_entity_ids(modified_entities)
wrapped_entity_ids = []
modified_entities.select { |e| e.respond_to?(:definition) }.each do |c|
wrapped_entity_ids += c.definition.entities.collect(&:persistent_id)
end
wrapped_entity_ids
end
# It is needed for attaching EntityObserver to newly added edges to track them with a hacky way.
# This hacky way is because of limitation on Sketchup API that observer cannot catch changes on Edges
# with EntitiesObserver.
def self.attach_edge_entity_observer(edges, observer)
edges.each do |edge|
edge.add_observer(observer)
edge.start.add_observer(observer)
edge.end.add_observer(observer)
end
end
end
# Event action when element modified.
class OnElementModified
# @param state [States::State] the current state of the SpeckleConnector Application
def self.update_state(state, event_data)
speckle_state = state.speckle_state
modified_entity = event_data[0][1]
if modified_entity.is_a?(Sketchup::Face)
path = state.sketchup_state.sketchup_model.active_path
modified_faces = SketchupModel::Utils::FaceUtils.near_faces(modified_entity.edges)
path_objects = path.nil? ? [] : path + path.collect(&:definition)
parent_ids = path_objects.collect(&:persistent_id)
ids_to_invalidate = modified_faces.collect(&:persistent_id) + parent_ids
entities_to_invalidate = speckle_entities_to_invalidate(speckle_state, ids_to_invalidate)
new_speckle_state = invalidate_speckle_entities(speckle_state, entities_to_invalidate)
# This is the place we can send information to UI for diffing check
diffing = state.user_state.preferences[:user][:diffing]
new_speckle_state = new_speckle_state.with_invalid_streams_queue if diffing
return state.with_speckle_state(new_speckle_state)
end
modified_entities = event_data.collect { |data| data[1] }.to_a
definition_faces = get_definition_faces(modified_entities)
modified_entity_ids = modified_entities.collect(&:persistent_id) + definition_faces.collect(&:persistent_id)
parent_ids = PATH.parents_with_definitions(state.sketchup_state.sketchup_model).collect(&:persistent_id)
path_instance_ids = PATH.instances(state.sketchup_state.sketchup_model).collect(&:persistent_id)
modified_entity_ids += parent_ids + path_instance_ids
state = EntitiesEventAction.run_expiration_checks(state, modified_entity_ids)
# if modified_entity.is_a?(Sketchup::Face)
# path = state.sketchup_state.sketchup_model.active_path
# modified_faces = SketchupModel::Utils::FaceUtils.near_faces(modified_entity.edges)
# path_objects = path.nil? ? [] : path + path.collect(&:definition)
# parent_ids = path_objects.collect(&:persistent_id)
# ids_to_invalidate = modified_faces.collect(&:persistent_id) + parent_ids
# entities_to_invalidate = speckle_entities_to_invalidate(speckle_state, ids_to_invalidate)
# new_speckle_state = invalidate_speckle_entities(speckle_state, entities_to_invalidate)
# # This is the place we can send information to UI for diffing check
# diffing = state.user_state.preferences[:user][:diffing]
# new_speckle_state = new_speckle_state.with_invalid_streams_queue if diffing
# return state.with_speckle_state(new_speckle_state)
# end
state
end
def self.get_near_faces(modified_entities)
near_faces = []
modified_entities.each do |modified_entity|
next unless modified_entity.is_a?(Sketchup::Face)
near_faces += SketchupModel::Utils::FaceUtils.near_faces(modified_entity.edges)
end
near_faces
end
def self.get_definition_faces(modified_entities)
definition_faces = []
modified_entities.each do |modified_entity|
next unless modified_entity.is_a?(Sketchup::Face)
next unless modified_entity.parent.is_a?(Sketchup::ComponentDefinition)
definition_faces += modified_entity.parent.entities.grep(Sketchup::Face)
end
definition_faces
end
# @param speckle_state [States::SpeckleState] the current state of the Speckle
def self.speckle_entities_to_invalidate(speckle_state, ids)
speckle_state.speckle_entities.to_h.select { |id, _| ids.include?(id) }
@@ -62,12 +123,22 @@ module SpeckleConnector
# Event action when element removed.
class OnElementRemoved
# @param state [States::State] the current state of the SpeckleConnector Application
def self.update_state(state, _event_data)
# TODO: Do state updates when element removed
state
def self.update_state(state, event_data)
modified_entity_ids = event_data.collect { |data| data[1] }.to_a
new_speckle_state = state.speckle_state.with_changed_entity_ids(modified_entity_ids)
state = state.with_speckle_state(new_speckle_state)
Actions::SendCardExpirationCheck.update_state(state)
end
end
# @param state [States::State] the current state of the SpeckleConnector Application
# @param changed_entity_ids [Array<Integer> | Array<String>] list of changed entity ids
def self.run_expiration_checks(state, changed_entity_ids)
new_speckle_state = state.speckle_state.with_changed_entity_persistent_ids(changed_entity_ids)
state = state.with_speckle_state(new_speckle_state)
Actions::SendCardExpirationCheck.update_state(state)
end
# Handlers that are used to handle specific events
ACTIONS = {
onElementRemoved: OnElementRemoved,
@@ -0,0 +1,51 @@
# frozen_string_literal: true
require_relative 'event_action'
require_relative '../../constants/dict_constants'
require_relative '../../sketchup_model/query/path'
module SpeckleConnector
module Actions
module Events
PATH = SketchupModel::Query::Path
# Event actions related to entities.
class EntityEventAction < EventAction
# Event action when entity modified/changed.
# PS: this handler action only triggers for edges and it's vertices since we attach EntityObserver to
# only edge and vertex entities. This is a limitation of the Sketchup API that can't handles edges with
# EntitiesObserver.
class OnChangeEntity
# @param state [States::State] the current state of the SpeckleConnector Application
def self.update_state(state, event_data)
edges = []
event_data.each do |event_d|
event_d.each do |d|
next if d.deleted?
edges.append(d) if d.is_a?(Sketchup::Edge)
edges += d.edges if d.is_a?(Sketchup::Vertex) && d.edges
end
end
parent_ids = PATH.parents_with_definitions(state.sketchup_state.sketchup_model).collect(&:persistent_id)
path_instance_ids = PATH.instances(state.sketchup_state.sketchup_model).collect(&:persistent_id)
edges.uniq!
edge_ids = edges.collect(&:persistent_id)
new_speckle_state = state.speckle_state.with_changed_entity_persistent_ids(edge_ids + parent_ids + path_instance_ids)
state.with_speckle_state(new_speckle_state)
end
end
# Handlers that are used to handle specific events
ACTIONS = {
onChangeEntity: OnChangeEntity
}.freeze
def self.actions
ACTIONS
end
end
end
end
end
@@ -18,12 +18,21 @@ module SpeckleConnector
sketchup_state = state.sketchup_state
active_path = sketchup_state.sketchup_model.active_path
observers = state.speckle_state.observers
update_object_observers(active_path, observers)
update_entity_observers(active_path, observers)
return state
end
def self.update_object_observers(path, observers)
path[-1].definition.entities.add_observer(observers[ENTITIES_OBSERVER]) unless path.nil?
def self.update_entity_observers(path, observers)
unless path.nil?
new_path_entities = path[-1].definition.entities
new_path_entities.add_observer(observers[ENTITIES_OBSERVER])
edges = new_path_entities.grep(Sketchup::Edge)
edges.each do |edge|
edge.add_observer(observers[ENTITY_OBSERVER])
edge.start.add_observer(observers[ENTITY_OBSERVER])
edge.end.add_observer(observers[ENTITY_OBSERVER])
end
end
end
end
@@ -0,0 +1,15 @@
# frozen_string_literal: true
module SpeckleConnector
module Actions
# Triggers whenever document has changed.
class OnDocumentChanged < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state)
js_command = "baseBinding.emit('documentChanged')"
state.with_add_queue_js_command('documentChanged', js_command)
end
end
end
end
@@ -2,6 +2,7 @@
require_relative 'event_action'
require_relative '../mapper_selection_changed'
require_relative '../selection_actions/get_selection'
require_relative '../../mapper/category/revit_category'
require_relative '../../sketchup_model/reader/speckle_entities_reader'
require_relative '../../sketchup_model/reader/mapper_reader'
@@ -17,12 +18,18 @@ module SpeckleConnector
def self.update_state(state, event_data)
return state unless event_data&.any?
# Get sketchup selection
sketchup_selection = state.sketchup_state.sketchup_model.selection
# POC: Not happy with it. We log also entity.entityID property since
# onElementRemoved observer only return them! :/ Reconsider this in BETA!
selected_object_ids = state.sketchup_state.sketchup_model.selection.collect(&:persistent_id) +
state.sketchup_state.sketchup_model.selection.collect(&:entityID)
summary = "Selected #{selected_object_ids.length / 2} objects." # POC: OFFF. I'll fix it
selection_info = UiData::Sketchup::SelectionInfo.new(selected_object_ids, summary)
js_script = "selectionBinding.emit('setSelection', #{selection_info.to_json})"
state.with_add_queue_js_command('setSelection', js_script)
# Collect and return mapper selection info.
# Later we can add more selection info for different scopes.
MapperSelectionChanged.new(sketchup_selection).update_state(state)
# MapperSelectionChanged.new(sketchup_selection).update_state(state)
end
end
end
@@ -0,0 +1,21 @@
# frozen_string_literal: true
require_relative 'action'
require_relative '../accounts/accounts'
require_relative 'load_saved_streams'
module SpeckleConnector
module Actions
# Action to initialize local accounts from database.
class GetAccounts < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
puts 'Initialisation of Speckle accounts requested by plugin'
accounts_data = state.speckle_state.accounts
js_script = "accountsBinding.receiveResponse('#{resolve_id}', #{accounts_data.to_json})"
state.with_add_queue_js_command('getAccounts', js_script)
end
end
end
end
@@ -0,0 +1,22 @@
# frozen_string_literal: true
require_relative 'action'
module SpeckleConnector
module Actions
# Get document info.
class GetDocumentInfo < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
document_info = {
location: state.sketchup_state.sketchup_model.path,
name: state.sketchup_state.sketchup_model.name,
id: state.sketchup_state.sketchup_model.guid
}
js_command = "baseBinding.receiveResponse('#{resolve_id}', #{document_info.to_json})"
state.with_add_queue_js_command('getDocumentInfo', js_command)
end
end
end
end
@@ -0,0 +1,31 @@
# frozen_string_literal: true
module SpeckleConnector
module Actions
# Action to return error message to UI.
class HandleError < Action
# @param error [String] error
# @param view_name [String] name of the view (binding)
# @param action [Action] action that error happened
# @param parameters [Array<String>] arguments
def initialize(error, view_name, action, parameters)
super()
@error = error
@view_name = view_name
@action = action
@args = parameters
end
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def update_state(state)
error_message = "Error: #{@error}\nBinding: #{@view_name}\nAction:#{@action}\nArgs: #{@args}\n"
error = {
error: error_message
}
js_error_script = "#{@view_name}.receiveResponse('#{@args.first}', #{error.to_json})"
state.with_add_queue_js_command("error_#{@view_name}", js_error_script)
end
end
end
end
@@ -10,7 +10,7 @@ module SpeckleConnector
class HideMappingsFromTable < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, data)
def self.update_state(state, _resolve_id, data)
# Flat entities to clear mappings
flat_entities = SketchupModel::Query::Entity.flat_entities(state.sketchup_state.sketchup_model.entities)
@@ -10,7 +10,7 @@ module SpeckleConnector
class InitLocalAccounts < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _request_id, _data)
puts 'Initialisation of Speckle accounts requested by plugin'
accounts_data = state.speckle_state.accounts
state.with_add_queue('loadAccounts', accounts_data.to_json, [])
@@ -7,6 +7,7 @@ require_relative '../states/sketchup_state'
require_relative '../accounts/accounts'
require_relative '../preferences/preferences'
require_relative '../constants/observer_constants'
require_relative '../ext/worker'
module SpeckleConnector
module Actions
@@ -14,7 +15,8 @@ module SpeckleConnector
class InitializeSpeckle < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, observers)
def self.update_state(state, observers, instant_message_sender)
worker = SpeckleConnector::Worker.new([])
attach_app_observer!(observers[APP_OBSERVER])
accounts = SpeckleConnector::Accounts.load_accounts
speckle_state = States::SpeckleState.new(accounts, observers, {}, {})
@@ -22,7 +24,8 @@ module SpeckleConnector
sketchup_state = States::SketchupState.new(Sketchup.active_model)
preferences = Preferences.read_preferences(sketchup_state.sketchup_model)
user_state_with_preferences = state.user_state.with_preferences(preferences)
state = States::State.new(user_state_with_preferences, speckle_state, sketchup_state, false)
state = States::State.new(user_state_with_preferences, speckle_state, sketchup_state, false,
worker, &instant_message_sender)
# This is where we attach observers to related model objects like selection, entities..
Actions::LoadSketchupModel.update_state(state, sketchup_state.sketchup_model)
end
@@ -14,7 +14,7 @@ module SpeckleConnector
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Metrics/CyclomaticComplexity
def self.update_state(state, data)
def self.update_state(state, _resolve_id, data)
sketchup_model = state.sketchup_state.sketchup_model
# Hide all entities first
@@ -8,7 +8,7 @@ module SpeckleConnector
class LoadSavedStreams < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _request_id, _data)
(saved_streams = state.sketchup_state.sketchup_model
.attribute_dictionary('Speckle', true)['saved_streams']) or []
state.with_add_queue('setSavedStreams', saved_streams, [])
@@ -29,6 +29,8 @@ module SpeckleConnector
# Read speckle entities
new_speckle_entities = SketchupModel::Reader::SpeckleEntitiesReader.read(sketchup_model.entities)
new_speckle_state = new_state.speckle_state.with_speckle_entities(Immutable::Hash.new(new_speckle_entities))
# POC: Reconsider it when we will do caching between sessions!
new_speckle_state = new_speckle_state.with_empty_object_references
# Read mapped entities
new_mapped_entities = SketchupModel::Reader::MapperReader.read_mapped_entities(sketchup_model.entities)
new_speckle_state = new_speckle_state.with_mapped_entities(Immutable::Hash.new(new_mapped_entities))
@@ -51,6 +53,8 @@ module SpeckleConnector
# layers = sketchup_model.layers
# layers.add_observer(observers[LAYERS_OBSERVER_NAME])
entities = sketchup_model.entities
edges = entities.grep(Sketchup::Edge)
edges.each { |edge| edge.add_observer(observers[ENTITY_OBSERVER]) }
entities.add_observer(observers[ENTITIES_OBSERVER])
sketchup_model.add_observer(observers[MODEL_OBSERVER])
# materials = sketchup_model.materials
@@ -9,7 +9,7 @@ module SpeckleConnector
class MappedEntitiesUpdated < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data = nil)
def self.update_state(state, _resolve_id = nil, _data = nil)
mapped_entities = SketchupModel::Reader::MapperReader
.mapped_entity_details(state.speckle_state.speckle_mapper_state.mapped_entities.values.to_a)
@@ -0,0 +1,22 @@
# frozen_string_literal: true
require_relative 'action'
require_relative '../mapper/category/revit_category'
require_relative '../mapper/category/revit_family_category'
module SpeckleConnector
module Actions
# Collects mapper selection info.
class MapperInitialized < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
init_parameters = {
categories: Mapper::Category::RevitCategory.to_a,
familyCategories: Mapper::Category::RevitFamilyCategory.to_a
}.freeze
state.with_mapper_init_queue(init_parameters)
end
end
end
end
@@ -2,6 +2,7 @@
require_relative 'action'
require_relative '../mapper/category/revit_category'
require_relative '../mapper/category/revit_family_category'
require_relative '../sketchup_model/reader/mapper_reader'
require_relative '../sketchup_model/reader/speckle_entities_reader'
require_relative '../sketchup_model/dictionary/speckle_entity_dictionary_handler'
@@ -35,6 +36,7 @@ module SpeckleConnector
end
def get_mapping_info(state, selection)
source_exist = !state.speckle_state.speckle_mapper_state.mapper_source.nil?
selection = filter_out_levels(selection)
grouped_by_type = group_by_type(selection)
@@ -45,10 +47,23 @@ module SpeckleConnector
# Return Direct Shape itself if multiple kinds of element are selected like Edge and Face.
# OR single type is equal to only direct shape supports.
return multiple_supported_selection_info(selection) if supported_entity_count > 1
# FIXME: Distinguish selection info according to selection elegantly!!!
if grouped_by_type.keys.first == Sketchup::ComponentInstance
return component_selection_info(selection, source_exist)
end
return group_selection_info(selection) if grouped_by_type.keys.first == Sketchup::Group
if supported_entity_count > 1 ||
(supported_entity_count == 1 &&
MAPPER_DIRECT_SHAPE_SUPPORTED_ENTITY_TYPES.include?(grouped_by_type.keys.first))
return direct_shape_selection_info(selection)
if source_exist
return direct_shape_selection_info_with_source(selection, [])
else
return direct_shape_selection_info(selection, source_exist)
end
end
# Only single type selections remained after this point.
@@ -73,29 +88,54 @@ module SpeckleConnector
EMPTY_SELECTION = {
selection: [],
mappingMethods: [],
categories: []
mappingMethods: []
}.freeze
def direct_shape_selection_info(selection)
def multiple_supported_selection_info(selection)
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: ['Direct Shape'],
categories: Mapper::Category::RevitCategory.to_a
mappingMethods: ['Direct Shape']
}.freeze
end
def component_selection_info(selection, source_exist)
if source_exist
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: ['Direct Shape', 'New Revit Family', 'Family Instance']
}.freeze
else
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: ['Direct Shape', 'New Revit Family']
}.freeze
end
end
def group_selection_info(selection)
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: ['Direct Shape']
}.freeze
end
def direct_shape_selection_info(selection, source_exist)
methods = ['Direct Shape', 'New Revit Family']
methods.append('Family Instance') if source_exist
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: methods
}.freeze
end
def direct_shape_selection_info_with_default(selection, methods)
{
selection: SketchupModel::Reader::MapperReader.entities_schema_details(selection),
mappingMethods: ['Direct Shape'] + methods,
categories: Mapper::Category::RevitCategory.to_a
mappingMethods: ['Direct Shape'] + methods
}.freeze
end
def direct_shape_selection_info_with_source(state, filtered_selection, methods)
types = state.speckle_state.speckle_mapper_state.mapper_source.types
levels = state.speckle_state.speckle_mapper_state.mapper_source.levels
def direct_shape_selection_info_with_source(filtered_selection, methods)
instances = @selection.grep(Sketchup::ComponentInstance)
selected_level = instances.find do |i|
DICTIONARY::SpeckleEntityDictionaryHandler
@@ -109,8 +149,6 @@ module SpeckleConnector
selection: READER::MapperReader.entities_schema_details(filtered_selection),
mappingMethods: ['Direct Shape'] + methods,
categories: Mapper::Category::RevitCategory.to_a,
types: types,
levels: levels,
selectedLevelName: selected_level_name
}.freeze
end
@@ -119,13 +157,13 @@ module SpeckleConnector
def face_selection_info(state, faces)
source_exist = !state.speckle_state.speckle_mapper_state.mapper_source.nil?
grouped_by_verticality = faces.group_by { |face| face.normal.perpendicular?(VECTOR_Z) }
return direct_shape_selection_info(faces) if grouped_by_verticality.length == 2
return direct_shape_selection_info(faces, source_exist) if grouped_by_verticality.length == 2
if source_exist
if grouped_by_verticality.keys.first
direct_shape_selection_info_with_source(state, faces, ['Wall'])
direct_shape_selection_info_with_source(faces, ['Wall'])
else
direct_shape_selection_info_with_source(state, faces, ['Floor'])
direct_shape_selection_info_with_source(faces, ['Floor'])
end
else
if grouped_by_verticality.keys.first
@@ -141,7 +179,7 @@ module SpeckleConnector
if source_exist
methods = ['Column', 'Beam', 'Pipe', 'Duct']
direct_shape_selection_info_with_source(state, edges, methods)
direct_shape_selection_info_with_source(edges, methods)
else
default_methods = ['Default Column', 'Default Beam', 'Default Pipe', 'Default Duct']
direct_shape_selection_info_with_default(edges, default_methods)
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require_relative 'action'
require_relative '../constants/type_constants'
require_relative '../mapper/mapper_source'
require_relative '../speckle_objects/built_elements/revit/revit_element_type'
@@ -20,13 +21,15 @@ module SpeckleConnector
def update_state(state)
levels = convert_levels(state, @base['@Levels'])
types = convert_types(@base['@Types'])
family_instances = convert_family_instance_types(@base['@Types'])
mapper_source = Mapper::MapperSource.new(@stream_id, @commit_id, levels, types)
new_speckle_state = state.speckle_state.with_mapper_source(mapper_source)
state = state.with_speckle_state(new_speckle_state)
state.with_add_queue('mapperSourceUpdated', @stream_id, [
{ is_string: false, val: levels.to_json },
{ is_string: false, val: types.to_json }
{ is_string: false, val: types.to_json },
{ is_string: false, val: family_instances.to_json }
])
end
@@ -43,6 +46,27 @@ module SpeckleConnector
end.compact.to_h
end
def convert_family_instance_types(types)
family_instance_types = {}
types.each do |type, type_elements|
next if type_elements.nil? || !type_elements.is_a?(Array) || type == '__closure'
# skip type if there is no any revit symbol element type
symbol_element_types = type_elements.select do |t|
t['speckle_type'] == OBJECTS_BUILTELEMENTS_REVIT_REVITSYMBOLELEMENTTYPE &&
t['placementType'] == 'OneLevelBased'
end
next if symbol_element_types.empty?
elements = type_elements.map do |type_element|
SpeckleObjects::BuiltElements::Revit::RevitElementType.to_native(type_element)
end
elements = elements.group_by { |e| e[:family] }
family_instance_types.merge!(elements)
end
family_instance_types
end
def convert_levels(state, levels)
levels.collect do |level|
SpeckleObjects::BuiltElements::Level.to_native(state, level, @stream_id)
@@ -3,6 +3,7 @@
require_relative 'action'
require_relative 'events/app_event_action'
require_relative 'events/entities_event_action'
require_relative 'events/entity_event_action'
require_relative 'events/model_event_action'
require_relative 'events/selection_event_action'
require_relative '../constants/observer_constants'
@@ -13,6 +14,7 @@ module SpeckleConnector
class OnEventsAction < Action
RUN_ORDER = {
APP_OBSERVER => Events::AppEventAction,
ENTITY_OBSERVER => Events::EntityEventAction,
ENTITIES_OBSERVER => Events::EntitiesEventAction,
MODEL_OBSERVER => Events::ModelEventAction,
# MATERIALS_OBSERVER => Events::MaterialsEventAction,
@@ -1,45 +0,0 @@
# frozen_string_literal: true
require_relative 'action'
require_relative '../accounts/accounts'
require_relative '../actions/create_stream'
require_relative '../actions/queue_send'
require_relative '../convertors/to_speckle'
module SpeckleConnector
module Actions
# Sends to speckle.
class OneClickSend < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state)
puts 'send to speckle'
default_account = Accounts.default_account
if default_account.nil?
puts 'No local account found. Please refer to speckle.guide for more information.'
return state
end
sketchup_model = state.sketchup_state.sketchup_model
to_convert = sketchup_model.selection.count > 0 ? sketchup_model.selection : sketchup_model.entities
first_saved_stream = first_saved_stream(sketchup_model)
action = if first_saved_stream.nil?
Actions::CreateStream.new
else
Actions::QueueSend.new(first_saved_stream, convert_to_speckle(sketchup_model, to_convert))
end
action.update_state(state)
end
def self.first_saved_stream(model)
(saved_streams = model.attribute_dictionary('speckle', true)['streams']) or []
saved_streams.nil? || saved_streams.empty? ? nil : saved_streams[0]
end
def self.convert_to_speckle(sketchup_model, to_convert)
converter = Converters::ToSpeckle.new(sketchup_model)
to_convert.map { |entity| converter.convert(entity) }
end
end
end
end
@@ -0,0 +1,18 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Action to let sketchup know receive from server is finished..
class AfterReceive < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, stream_id, root_id)
puts "receive finished for: #{root_id}"
js_script = "sketchupReceiveBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('afterReceive', js_script)
end
end
end
end
@@ -0,0 +1,18 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Action to let sketchup know receive will be started.
class BeforeReceive < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, stream_id, root_id)
puts "receive started for: #{root_id}"
js_script = "sketchupReceiveBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('beforeReceive', js_script)
end
end
end
end
@@ -0,0 +1,91 @@
# frozen_string_literal: true
require 'json'
require_relative '../action'
require_relative '../../convertors/units'
require_relative '../../convertors/to_native'
module SpeckleConnector
module Actions
# Clear mappings for selected entities.
class ReceiveSingleObject < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, stream_id, root_id, speckle_objects)
puts "object receive #{speckle_objects.length}"
buffer = speckle_objects.collect { |obj| [obj['id'], obj] }.to_h
t_0 = Time.now.to_f
root_obj = traverse_and_construct(speckle_objects.first, buffer)
puts root_obj
puts "Elapsed traverse and construct #{Time.now.to_f - t_0}"
# File.open("#{ENV['HOME']}/OneDrive/Masaüstü/root.json", 'w') do |f|
# f.write(JSON.pretty_generate(root_obj))
# end
# converter = Converters::ToNative.new(state, stream_id, 'test', 'testt', 'test')
# state = converter.receive_commit_object(root_obj)
js_script = "sketchupReceiveBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('receiveObject', js_script)
end
def self.traverse_and_construct(obj, buffer)
return if obj.nil?
return obj if !obj.is_a?(Hash) && !obj.is_a?(Array)
# Handle arrays
if obj.is_a?(Array) && !obj.empty?
arr = handle_array(buffer, obj)
# De-chunk, if array is a set of datachunk, flat them into single data chunk.
arr = try_dechunk(arr)
return arr
end
# Handle object
obj = handle_hash(buffer, obj)
return obj
rescue StandardError => e
puts "#{e} -> #{obj}"
return nil
end
def self.handle_array(buffer, obj)
arr = []
obj.collect do |element|
next if element.nil?
deref = element.is_a?(Hash) && !element['referencedId'].nil? ? buffer[element['referencedId']] : element
arr.append(traverse_and_construct(deref, buffer))
end
arr
end
def self.try_dechunk(arr)
if arr[0].is_a?(Hash) && !arr[0]['speckle_type'].nil? && arr[0]['speckle_type'].downcase.include?('datachunk')
sum_arr = []
arr.each do |chunk|
sum_arr += chunk['data']
end
sum_arr
else
arr
end
end
def self.handle_hash(buffer, obj)
obj.each do |prop, value|
next if value.nil? || (!value.is_a?(Hash) && !value.is_a?(Array))
obj[prop] = buffer[value['referencedId']] if value.is_a?(Hash) && value['referencedId']
obj[prop] = traverse_and_construct(obj[prop], buffer)
end
obj
end
end
end
end
@@ -0,0 +1,56 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../convertors/to_native'
require_relative '../../convertors/to_native_v2'
module SpeckleConnector
module Actions
# Receive from server.
class AfterGetObjects < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, model_card_id, source_application, root_obj)
model_card = state.speckle_state.receive_cards[model_card_id]
state.sketchup_state.sketchup_model.start_operation('Receive Speckle Objects', true)
# TODO: CONVERTER_V2: Remove later if statement and make V2 default.
converter = if root_obj['instanceDefinitionProxies']
Converters::ToNativeV2.new(state, root_obj['instanceDefinitionProxies'], source_application,
model_card)
else
Converters::ToNative.new(state, model_card.model_id, model_card.project_name,
model_card.model_name, source_application, model_card_id)
end
# converter = Converters::ToNative.new(state, model_card.model_id, model_card.project_name,
# model_card.model_name, source_application, model_card_id)
start_time = Time.now.to_f
# Have side effects on the sketchup model. It effects directly on the entities by adding new objects.
state = converter.receive_commit_object(root_obj)
if state.user_state.model_preferences[:merge_coplanar_faces]
Converters::CleanUp.merge_coplanar_faces(converter.converted_faces)
end
elapsed_time = (Time.now.to_f - start_time).round(3)
state.sketchup_state.sketchup_model.commit_operation
puts "==== Converting to Native executed in #{elapsed_time} sec ===="
puts "==== Source application is #{@source_app}. ===="
# Where we send info about received top level (for the sake of handling with less) objects.
top_objects = converter.converted_entities.reject(&:deleted?).select { |e| e.parent.is_a?(Sketchup::Model) }
top_object_ids = top_objects.collect(&:persistent_id)
args = {
modelCardId: model_card_id,
bakedObjectIds: top_object_ids,
conversionResults: converter.conversion_results
}
# TODO: set here bakedObjectIds when we get rid of patching model as post receive action.
receive_result_js_script = "receiveBinding.emit('setModelReceiveResult', #{args.to_json})"
state = state.with_add_queue_js_command('setModelReceiveResult', receive_result_js_script)
resolve_js_script = "receiveBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('receive', resolve_js_script)
end
end
end
end
@@ -0,0 +1,31 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../accounts/accounts'
require_relative '../../convertors/units'
require_relative '../../convertors/to_speckle'
require_relative '../../operations/send'
module SpeckleConnector
module Actions
# Receive from server.
class Receive < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, model_card_id)
model_card = state.speckle_state.receive_cards[model_card_id]
resolve_js_script = "receiveBinding.receiveResponse('#{resolve_id}')"
state = state.with_add_queue_js_command('receive', resolve_js_script)
args = {
modelCardId: model_card_id,
projectId: model_card.project_id,
accountId: model_card.account_id,
modelId: model_card.model_id,
selectedVersionId: model_card.selected_version_id
}
js_script = "receiveBinding.emit('receiveViaBrowser', #{args.to_json})"
state.with_add_queue_js_command('receiveViaBrowser', js_script)
end
end
end
end
@@ -3,6 +3,7 @@
require_relative 'action'
require_relative '../convertors/units'
require_relative '../convertors/to_native'
require_relative '../operations/receive'
require_relative '../convertors/clean_up'
module SpeckleConnector
@@ -10,7 +11,7 @@ module SpeckleConnector
# Action to receive objects from Speckle Server.
class ReceiveObjects < Action
# rubocop:disable Metrics/ParameterLists
def initialize(stream_id, base, stream_name, branch_name, branch_id, source_app)
def initialize(stream_id, base, stream_name, branch_name, branch_id, source_app, object_id)
super()
@stream_id = stream_id
@base = base
@@ -18,12 +19,15 @@ module SpeckleConnector
@branch_name = branch_name
@branch_id = branch_id
@source_app = source_app
@object_id = object_id
end
# rubocop:enable Metrics/ParameterLists
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def update_state(state)
# content = Operations.receive(@stream_id, @object_id)
converter = Converters::ToNative.new(state, @stream_id, @stream_name, @branch_name, @source_app)
# Have side effects on the sketchup model. It effects directly on the entities by adding new objects.
start_time = Time.now.to_f
@@ -10,7 +10,7 @@ module SpeckleConnector
class ReloadAccounts < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
puts 'Reload of Speckle accounts requested by plugin'
new_speckle_state = state.speckle_state.with_accounts(Accounts.load_accounts)
state = state.with_speckle_state(new_speckle_state)
@@ -10,11 +10,11 @@ module SpeckleConnector
class SelectMappingsFromTable < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, data)
def self.update_state(state, _resolve_id, data)
# Clear first selection
state.sketchup_state.sketchup_model.selection.clear
# Flat entities to clear mappings
# Flat entities to select mapped elements
flat_entities = SketchupModel::Query::Entity.flat_entities(state.sketchup_state.sketchup_model.entities)
# Collect entity ids to clear mappings
@@ -0,0 +1,24 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../ui_data/sketchup/selection_info'
module SpeckleConnector
module Actions
# Action to get selection.
class GetSelection < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
# POC: Not happy with it. We log also entity.entityID property since
# onElementRemoved observer only return them! :/ Reconsider this in BETA!
selected_object_ids = state.sketchup_state.sketchup_model.selection.collect(&:persistent_id) +
state.sketchup_state.sketchup_model.selection.collect(&:entityID) # That's bad
summary = "Selected #{selected_object_ids.length / 2} objects." # POC: OFFF. I'll fix it
selection_info = UiData::Sketchup::SelectionInfo.new(selected_object_ids, summary)
js_script = "selectionBinding.receiveResponse('#{resolve_id}', #{selection_info.to_json})"
state.with_add_queue_js_command('getSelection', js_script)
end
end
end
end
@@ -0,0 +1,22 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to activate send filter.
class ActivateSendFilter < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data, value)
SketchupModel::Dictionary::ModelCardDictionaryHandler.update_filter(state.sketchup_state.sketchup_model, data, value)
card_id = "#{data['accountId']}-#{data['projectId']}-#{data['modelId']}"
send_card = state.speckle_state.send_cards[card_id]
puts "Send card filter updated -> #{card_id} -> #{send_card}"
js_script = "sendBindingOld.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('activateSendFilter', js_script)
end
end
end
end
@@ -0,0 +1,22 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to activate send filter tag.
class ActivateSendFilterTag < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, data, value)
SketchupModel::Dictionary::ModelCardDictionaryHandler.update_tag_filter(state.sketchup_state.sketchup_model, data, value)
card_id = "#{data['accountId']}-#{data['projectId']}-#{data['modelId']}"
send_card = state.speckle_state.send_cards[card_id]
puts "Send card filter updated -> #{card_id} -> #{send_card}"
js_script = "sendBindingOld.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('activateSendFilterTag', js_script)
end
end
end
end
@@ -0,0 +1,77 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../accounts/accounts'
require_relative '../../convertors/units'
require_relative '../../convertors/to_speckle_v2'
require_relative '../../operations/send'
require_relative '../../sketchup_model/definitions/definition_manager'
module SpeckleConnector
module Actions
# Send to server.
class Send < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, model_card_id)
# Set active path always to model to be safe always. Later we can address it
state.sketchup_state.sketchup_model.active_path = nil
model_card = state.speckle_state.send_cards[model_card_id]
unless model_card.send_filter.selected_object_ids.any?
resolve_js_script = "sendBinding.receiveResponse('#{resolve_id}')"
state = state.with_add_queue_js_command('resolveSend', resolve_js_script)
args = {
modelCardId: model_card_id,
error: 'No objects were found. Please update your send filter!'
}
js_script = "sendBinding.emit('setModelError', #{args.to_json})"
return state.with_add_queue_js_command('setModelsError', js_script)
end
entities = state.sketchup_state.sketchup_model.entities.select do |e|
model_card.send_filter.selected_object_ids.any?(e.persistent_id)
end
unpacked_entities = SketchupModel::Definitions::DefinitionManager
.new(Converters::SKETCHUP_UNITS[state.sketchup_state.length_units])
.unpack_entities(entities)
account = Accounts.get_account_by_id(model_card.account_id)
converter = Converters::ToSpeckleV2.new(state, unpacked_entities, model_card)
new_speckle_state, base = converter.convert_entities_to_base_blocks_poc
base[:instanceDefinitionProxies] = unpacked_entities.instance_definition_proxies
id, total_children_count, batches, refs = converter.serialize(base, state.user_state.preferences)
new_speckle_state = new_speckle_state.with_object_references(model_card.project_id, refs)
new_speckle_state = new_speckle_state.with_empty_changed_entity_persistent_ids
new_speckle_state = new_speckle_state.with_empty_changed_entity_ids
puts("converted #{base.count} objects for stream #{model_card.project_id}")
state = state.with_speckle_state(new_speckle_state)
resolve_js_script = "sendBinding.receiveResponse('#{resolve_id}')"
state = state.with_add_queue_js_command('send', resolve_js_script)
args = {
modelCardId: model_card_id,
projectId: model_card.project_id,
modelId: model_card.model_id,
token: account['token'],
serverUrl: account['serverInfo']['url'],
accountId: model_card.account_id,
message: model_card.message,
sendConversionResults: converter.conversion_results,
sendObject: {
id: id,
totalChildrenCount: total_children_count,
batches: batches
}
}
js_script = "sendBinding.emit('sendViaBrowser', #{args.to_json})"
state.with_add_queue_js_command('sendViaBrowser', js_script)
end
end
end
end
@@ -0,0 +1,24 @@
# frozen_string_literal: true
require_relative '../action'
require_relative '../../sketchup_model/dictionary/model_card_dictionary_handler'
module SpeckleConnector
module Actions
# Action to check send card expirations.
class SendCardExpirationCheck < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state)
return state unless state.speckle_state.changed_entity_persistent_ids.any? || state.speckle_state.changed_entity_ids.any?
expired_send_cards_ids = state.speckle_state.send_cards.select do |_id, send_card|
send_card.send_filter.check_expiry(state.speckle_state.changed_entity_persistent_ids) ||
send_card.send_filter.check_expiry(state.speckle_state.changed_entity_ids)
end.keys.to_a
js_script = "sendBinding.emit('setModelsExpired', #{expired_send_cards_ids.to_json})"
state.with_add_queue_js_command('setModelsExpired', js_script)
end
end
end
end
@@ -4,6 +4,7 @@ require_relative 'action'
require_relative 'deactivate_diffing'
require_relative '../convertors/units'
require_relative '../convertors/to_speckle'
require_relative '../operations/send'
module SpeckleConnector
module Actions
@@ -17,11 +18,13 @@ module SpeckleConnector
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def update_state(state)
state = DeactivateDiffing.update_state(state, {})
converter = Converters::ToSpeckle.new(state, @stream_id)
new_speckle_state, base = converter.convert_selection_to_base(state.user_state.preferences)
id, total_children_count, batches, new_speckle_state = converter.serialize(base, new_speckle_state,
state.user_state.preferences)
state = DeactivateDiffing.update_state(state, nil, {})
converter = Converters::ToSpeckle.new(state, @stream_id, {})
new_speckle_state, base = converter.convert_selection_to_base
id, total_children_count, batches = converter.serialize(base, state.user_state.preferences)
# TODO: Later active send operation.
# Operations.send(@stream_id, batches)
puts("converted #{base.count} objects for stream #{@stream_id}")
# This is the place we can send information to UI for diffing check
@@ -8,7 +8,7 @@ module SpeckleConnector
class ShowAllEntities < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, _data)
def self.update_state(state, _resolve_id, _data)
# Show all entities first
state.sketchup_state.sketchup_model.entities.each do |ent|
ent.hidden = false
@@ -0,0 +1,46 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Action to get user config.
class GetUserConfig < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
# Previously it was stored in user state
# config = state.user_state.preferences.to_json
config = [
{
key: 'darkTheme',
title: 'Theme',
type: 'toggle',
config: {
value: state.user_state.user_preferences[:dark_theme]
}
},
{
key: 'diffing',
title: 'Diffing',
type: 'toggle',
config: {
value: state.user_state.user_preferences[:diffing]
}
},
{
key: 'referencePoint',
title: 'Reference Point',
type: 'dropdown',
config: {
value: 'test',
items: ['test', 'test1', 'test2']
}
}
]
js_script = "connectorConfigBinding.receiveResponse('#{resolve_id}', #{config.to_json})"
state.with_add_queue_js_command('getUserConfig', js_script)
end
end
end
end
@@ -0,0 +1,18 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Action to get user config.
class UpdateUserConfig < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, new_config)
puts new_config.values
js_script = "connectorConfigBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('updateUserConfig', js_script)
end
end
end
end
@@ -0,0 +1,21 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Test purpose action.
class GetComplexType < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
complex_type = {
id: 'complex_type_id',
count: 3
}
js_script = "testBinding.receiveResponse('#{resolve_id}', #{complex_type.to_json})"
state.with_add_queue_js_command('getComplexType', js_script)
end
end
end
end
@@ -0,0 +1,18 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Test purpose action.
class GoAway < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id)
puts 'SketchUp went away :('
js_script = "testBinding.receiveResponse('#{resolve_id}')"
state.with_add_queue_js_command('goAway', js_script)
end
end
end
end
@@ -0,0 +1,21 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Test purpose action.
class SayHi < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, name, count, say_hello_not_hi)
said_hi = []
count.times do
said_hi.append("#{say_hello_not_hi ? 'Hello' : 'Hi'} #{name}!")
end
js_script = "testBinding.receiveResponse('#{resolve_id}', #{said_hi})"
state.with_add_queue_js_command('sayHi', js_script)
end
end
end
end
@@ -0,0 +1,28 @@
# frozen_string_literal: true
require_relative '../action'
module SpeckleConnector
module Actions
# Test purpose action.
class TriggerEvent < Action
# @param state [States::State] the current state of the {App::SpeckleConnectorApp}
# @return [States::State] the new updated state object
def self.update_state(state, resolve_id, event_name)
if event_name == 'emptyTestEvent'
js_script = "testBinding.emit('#{event_name}')"
else
args = {
name: 'Oguzhan',
isOk: true,
count: 3
}
js_script = "testBinding.emit('#{event_name}', #{args.to_json})"
end
resolve_js_script = "testBinding.receiveResponse('#{resolve_id}')"
state = state.with_add_queue_js_command('triggerEventResolve', resolve_js_script)
state.with_add_queue_js_command('triggerEvent', js_script)
end
end
end
end
@@ -28,10 +28,6 @@ module SpeckleConnector
state.speckle_state?
end
def update_ui!
ui_controller.update_ui(state)
end
# Attach observers to application when speckle initialized via menu commands.
def add_observer_handler!(observer_handler)
@observer_handler = observer_handler
@@ -40,17 +36,24 @@ module SpeckleConnector
# Send messages to HtmlDialog if any.
def send_messages!
queue = @state.speckle_state.message_queue
queue.each_value { |value| ui_controller.user_interfaces[Ui::SPECKLE_UI_ID].dialog.execute_script(value) }
queue.each_value do |value|
instant_message_sender(value)
end
update_state!(Actions::ClearQueue)
end
def instant_message_sender(message)
ui_controller.user_interfaces.each_value do |dialog|
dialog.execute_script(message)
end
end
# This is the only function application state will be switched by calling upcoming action with it's parameters
# if any.
def update_state!(action, *parameters)
old_state = @state
@state = action.update_state(old_state, *parameters)
send_messages! if @state.speckle_state.message_queue.any?
update_ui! unless @state.equal?(old_state)
end
end
end
+51
View File
@@ -0,0 +1,51 @@
# frozen_string_literal: true
require_relative '../speckle_objects/other/color'
module SpeckleConnector
module Cards
# Card for sketchup connector to communicate speckle.
class Card < Hash
# @return [String] id of the card.
attr_reader :model_card_id
# @return [String] account id of the card.
attr_reader :account_id
# @return [String] project name of the card.
attr_reader :project_name
# @return [String] project id of the card.
attr_reader :project_id
# @return [String] model id of the card.
attr_reader :model_id
# @return [String] model name of the card.
attr_reader :model_name
# @return [Boolean] card is valid or not.
attr_reader :valid
# rubocop:disable Metrics/ParameterLists
def initialize(model_card_id, account_id, project_id, project_name, model_id, model_name)
super()
@model_card_id = model_card_id
@account_id = account_id
@project_id = project_id
@project_name = project_name
@model_id = model_id
@model_name = model_name
@valid = true
self[:model_card_id] = model_card_id
self[:account_id] = account_id
self[:project_id] = project_id
self[:project_name] = project_name
self[:model_id] = model_id
self[:model_name] = model_name
self[:valid] = @valid
end
# rubocop:enable Metrics/ParameterLists
end
end
end
@@ -0,0 +1,70 @@
# frozen_string_literal: true
require_relative 'card'
module SpeckleConnector
module Cards
# Receive card for sketchup connector to communicate speckle.
class ReceiveCard < Card
attr_reader :type_discriminator
# @return [String, NilClass] message to send
attr_reader :message
# @return [String] selected version id to receive
attr_reader :selected_version_id
# @return [String] latest version id to receive
attr_reader :latest_version_id
# @return [Boolean] whether new version notification is dismissed or not
attr_reader :has_dismissed_update_warning
# @return [String] name of the project
attr_reader :project_name
# @return [String] name of the model
attr_reader :model_name
# @return [String] whether card is expired or not
attr_reader :expired
# @return [Array<Integer>] object ids that baked after receive.
attr_reader :baked_object_ids
# rubocop:disable Metrics/ParameterLists
def initialize(
model_card_id,
account_id,
project_id,
model_id,
project_name,
model_name,
selected_version_id,
latest_version_id,
has_dismissed_update_warning,
expired,
baked_object_ids = nil
)
super(model_card_id, account_id, project_id, project_name, model_id, model_name)
@selected_version_id = selected_version_id
@latest_version_id = latest_version_id
@has_dismissed_update_warning = has_dismissed_update_warning
@baked_object_ids = baked_object_ids
self[:selected_version_id] = selected_version_id
self[:has_dismissed_update_warning] = has_dismissed_update_warning
self[:latest_version_id] = latest_version_id
self[:model_name] = model_name
self[:project_name] = project_name
self[:expired] = expired
self[:baked_object_ids] = @baked_object_ids
@expired = expired
@model_name = model_name
@project_name = project_name
@type_discriminator = 'ReceiverModelCard'
self[:type_discriminator] = @type_discriminator
end
# rubocop:enable Metrics/ParameterLists
end
end
end
+50
View File
@@ -0,0 +1,50 @@
# frozen_string_literal: true
require_relative 'card'
module SpeckleConnector
module Cards
# Send card for sketchup connector to communicate speckle.
class SendCard < Card
# @return [Filters::Send::EverythingFilter | Filters::Send::SelectionFilter | Filters::Send::LayerFilter] filter of the card.
attr_reader :send_filter
# @return [Object] send settings of the card.
attr_reader :send_settings
attr_reader :type_discriminator
# @return [String, NilClass] message to send
attr_reader :message
# @return [Boolean] whether sending is happening or not
attr_reader :sending
attr_reader :latest_created_version_id
# rubocop:disable Metrics/ParameterLists
def initialize(
model_card_id,
account_id,
project_id,
project_name,
model_id,
model_name,
latest_created_version_id,
send_filter,
send_settings
)
super(model_card_id, account_id, project_id, project_name, model_id, model_name)
@send_filter = send_filter
@send_settings = send_settings
@latest_created_version_id = latest_created_version_id
@type_discriminator = 'SenderModelCard'
self[:sendFilter] = send_filter
self[:sendSettings] = send_settings
self[:latestCreatedVersionId] = latest_created_version_id
self[:type_discriminator] = @type_discriminator
end
# rubocop:enable Metrics/ParameterLists
end
end
end
@@ -0,0 +1,19 @@
# frozen_string_literal: true
require_relative 'card'
module SpeckleConnector
module Cards
# Send card for sketchup connector to communicate speckle.
class SendCardMultipleFilters < Card
# @return [Hash{String=>Filter}] filters of the card.
attr_reader :filters
def initialize(card_id, account_id, project_id, model_id, filters)
super(card_id, account_id, project_id, model_id)
@filters = filters
self[:filters] = filters
end
end
end
end
@@ -7,10 +7,10 @@ module SpeckleConnector
# Command to update state of the application.
class ActionCommand < Command
# @param app [App::SpeckleConnectorApp] the app object to run command on
# @param binding [Ui::Binding] binding object holds commands to call
# @param action [#update_state] the action that knows how to change the state of the speckle app
def initialize(app, action)
super(app)
@app = app
def initialize(app, binding, action)
super(app, binding)
@action = action
end
@@ -7,7 +7,7 @@ module SpeckleConnector
module Commands
# Command to activate diffing for stream.
class ActivateDiffing < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
action = Actions::ActivateDiffing.new(stream_id)
app.update_state!(action)
@@ -7,7 +7,7 @@ module SpeckleConnector
module Commands
# Command to apply mapping for selected entities.
class ApplyMappings < Command
def _run(data)
def _run(_resolve_id, data)
entities_to_map = data['entitiesToMap']
method = data['method']
category = data['category']
@@ -7,7 +7,7 @@ module SpeckleConnector
module Commands
# Command to clear mapping for selected entities.
class ClearMappings < Command
def _run(data)
def _run(_resolve_id, data)
entities_to_map = data['entitiesToClearMap']
is_definition = data['isDefinition']
action = Actions::ClearMappings.new(entities_to_map, is_definition)
+16 -8
View File
@@ -1,5 +1,7 @@
# frozen_string_literal: true
require_relative '../actions/handle_error'
module SpeckleConnector
module Commands
# Base command schema to wrap common operations for all commands.
@@ -7,19 +9,25 @@ module SpeckleConnector
# @return [App::SpeckleConnectorApp] the main app object
attr_reader :app
# @return [Ui::View] view object holds dialog and it's state
attr_reader :view
# @return [Ui::Binding] binding object holds dialog and it's state
attr_reader :binding
# @@param app [App::SpeckleConnectorApp] the main app object
def initialize(app)
# @param app [App::SpeckleConnectorApp] the main app object
# @param binding [Ui::Binding] binding object holds commands to call
def initialize(app, binding)
@app = app
@view = app.ui_controller.user_interfaces[Ui::SPECKLE_UI_ID]
@binding = binding
end
def run(*parameters)
# Run here common operations that same for each command.
with_observers_disabled do
_run(*parameters)
begin
# Run here common operations that same for each command.
with_observers_disabled do
_run(*parameters)
end
rescue StandardError => e
action = Actions::HandleError.new(e, @binding.name, @action, parameters)
app.update_state!(action)
end
end
@@ -1,15 +0,0 @@
# frozen_string_literal: true
require_relative 'command'
module SpeckleConnector
module Commands
# Run this command when the UI is ready to get data
class DialogReady < Command
# Update the selected user interface
def _run(_data)
view.update_view(app.state)
end
end
end
end
@@ -0,0 +1,85 @@
# frozen_string_literal: true
require_relative 'command'
require_relative '../ui/dui3_dialog'
require_relative '../states/initial_state'
require_relative '../ui/legacy_binding'
require_relative '../ui/bindings/accounts_binding'
require_relative '../ui/bindings/base_binding'
require_relative '../ui/bindings/send_binding'
require_relative '../ui/bindings/receive_binding'
require_relative '../ui/bindings/selection_binding'
require_relative '../ui/test_binding'
require_relative '../ui/bindings/config_binding'
require_relative '../ui/sketchup_config_binding'
require_relative '../actions/initialize_speckle'
require_relative '../observers/factory'
module SpeckleConnector
module Commands
# Command to initialize Speckle UI and register it to ui_controller.
# This is the command where we show UI to user.
class InitializeDUI3Speckle < Command
SPECKLE_DUI3 = 'speckle_dui3'
def dialog_title
"Speckle #{CONNECTOR_VERSION}"
end
private
def _run
app = self.app
if !app.state.instance_of?(States::InitialState) && app.ui_controller.user_interfaces[SPECKLE_DUI3]
dialog = app.ui_controller.user_interfaces[SPECKLE_DUI3]
dialog.show
return
end
initialize_speckle_dui3(app)
end
# Do the actual Speckle initialization.
# rubocop:disable Naming/VariableNumber
def initialize_speckle_dui3(app)
# TODO: Initialize here speckle states and observers.
observer_handler = Observers::Factory.create_handler(app)
app.add_observer_handler!(observer_handler)
observers = Observers::Factory.create_observers(observer_handler)
app.update_state!(Actions::InitializeSpeckle, observers, app.method(:instant_message_sender))
dialog_specs = {
dialog_id: SPECKLE_DUI3,
dialog_title: dialog_title,
height: 950,
width: 300
}
# Init bindings
base_binding = Ui::BaseBinding.new(app, Ui::BASE_BINDING_NAME)
accounts_binding = Ui::AccountsBinding.new(app, Ui::ACCOUNTS_BINDING_NAME)
send_binding = Ui::SendBinding.new(app, Ui::SEND_BINDING_NAME)
receive_binding = Ui::ReceiveBinding.new(app, Ui::RECEIVE_BINDING_NAME)
selection_binding = Ui::SelectionBinding.new(app, Ui::SELECTION_BINDING_NAME)
test_bindings = Ui::TestBinding.new(app, Ui::TEST_BINDINGS_NAME)
config_bindings = Ui::ConfigBinding.new(app, Ui::CONFIG_BINDING_NAME)
connector_config_bindings = Ui::SketchupConfigBinding.new(app, Ui::CONNECTOR_CONFIG_BINDING_NAME)
# Init dialog
dui3_dialog = SpeckleConnector::Ui::DUI3Dialog.new(**dialog_specs)
# Register bindings to dialog
dui3_dialog.bindings[Ui::BASE_BINDING_NAME] = base_binding
dui3_dialog.bindings[Ui::ACCOUNTS_BINDING_NAME] = accounts_binding
dui3_dialog.bindings[Ui::SEND_BINDING_NAME] = send_binding
dui3_dialog.bindings[Ui::RECEIVE_BINDING_NAME] = receive_binding
dui3_dialog.bindings[Ui::TEST_BINDINGS_NAME] = test_bindings
dui3_dialog.bindings[Ui::CONFIG_BINDING_NAME] = config_bindings
dui3_dialog.bindings[Ui::CONNECTOR_CONFIG_BINDING_NAME] = connector_config_bindings
dui3_dialog.bindings[Ui::SELECTION_BINDING_NAME] = selection_binding
app.ui_controller.register_ui(SPECKLE_DUI3, dui3_dialog)
dui3_dialog.show
end
# rubocop:enable Naming/VariableNumber
end
end
end
@@ -2,15 +2,17 @@
require_relative 'command'
require_relative '../states/initial_state'
require_relative '../ui/vue_view'
require_relative '../ui/legacy_binding'
require_relative '../actions/initialize_speckle'
require_relative '../observers/factory'
module SpeckleConnector
module Commands
# Command to initialize Speckle UI and register it to ui_controller.
# Command to initialize old Speckle UI and register it to ui_controller.
# This is the command where we show UI to user.
class InitializeSpeckle < Command
SPECKLE_LEGACY_UI = 'speckle_legacy_ui'
def dialog_title
"Speckle #{CONNECTOR_VERSION}"
end
@@ -19,32 +21,34 @@ module SpeckleConnector
def _run
app = self.app
unless app.state.instance_of?(States::InitialState)
vue_view = app.ui_controller.user_interfaces[Ui::SPECKLE_UI_ID]
if !app.state.instance_of?(States::InitialState) && app.ui_controller.user_interfaces[SPECKLE_LEGACY_UI]
vue_view = app.ui_controller.user_interfaces[SPECKLE_LEGACY_UI]
vue_view.show
return
end
initialize_speckle(app)
initialize_speckle_legacy_view(app)
end
# Do the actual Speckle initialization.
def initialize_speckle(app)
def initialize_speckle_legacy_view(app)
# TODO: Initialize here speckle states and observers.
observer_handler = Observers::Factory.create_handler(app)
app.add_observer_handler!(observer_handler)
observers = Observers::Factory.create_observers(observer_handler)
app.update_state!(Actions::InitializeSpeckle, observers)
dialog_specs = {
dialog_id: Ui::SPECKLE_UI_ID,
dialog_id: SPECKLE_LEGACY_UI,
htm_file: Ui::VUE_UI_HTML,
dialog_title: dialog_title,
height: 950,
width: 300
}
vue_view = Ui::VueView.new(dialog_specs, app)
app.ui_controller.register_ui(Ui::SPECKLE_UI_ID, vue_view)
vue_view.show
legacy_ui_dialog = SpeckleConnector::Ui::Dialog.new(**dialog_specs)
legacy_binding = Ui::LegacyBinding.new(app, 'legacy_ui')
legacy_ui_dialog.bindings[Ui::SPECKLE_LEGACY_BINDING_NAME] = legacy_binding
app.ui_controller.register_ui(SPECKLE_LEGACY_UI, legacy_ui_dialog)
legacy_ui_dialog.show
end
end
end
@@ -7,7 +7,7 @@ module SpeckleConnector
module Commands
# Command to update mapper source.
class MapperSourceUpdated < Command
def _run(data)
def _run(_resolve_id, data)
base = data['base']
stream_id = data['stream_id']
commit_id = data['commit_id']
@@ -8,7 +8,7 @@ module SpeckleConnector
module Commands
# Command to update theme.
class ModelPreferencesUpdated < Command
def _run(data)
def _run(_resolve_id, data)
preference = data['preference']
new_value = data['value']
app.update_state!(Actions::ModelPreferencesUpdated.new(preference, new_value))
@@ -8,7 +8,7 @@ module SpeckleConnector
module Commands
# Command to notify connected.
class NotifyConnected < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
app.update_state!(Actions::Connected)
app.update_state!(Actions::SendFromQueue.new(stream_id))
@@ -7,14 +7,15 @@ module SpeckleConnector
module Commands
# Command to receive objects from Speckle Server.
class ReceiveObjects < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
base = data['base']
branch_name = data['branch_name']
branch_id = data['branch_id']
stream_name = data['stream_name']
source_app = data['source_app']
action = Actions::ReceiveObjects.new(stream_id, base, stream_name, branch_name, branch_id, source_app)
object_id = data['object_id']
action = Actions::ReceiveObjects.new(stream_id, base, stream_name, branch_name, branch_id, source_app, object_id)
app.update_state!(action)
end
end
@@ -8,7 +8,7 @@ module SpeckleConnector
module Commands
# Command to remove stream.
class RemoveStream < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
action = Actions::RemoveStream.new(stream_id)
app.update_state!(action)
@@ -0,0 +1,26 @@
# frozen_string_literal: true
require_relative 'command'
require_relative '../states/initial_state'
require_relative '../actions/initialize_speckle'
require_relative '../observers/factory'
module SpeckleConnector
module Commands
# Command to reset Speckle UI window location onto center of SketchUp window.
class ResetWindowLocation < Command
private
def _run
app = self.app
vue_view = app.ui_controller.user_interfaces[Ui::SPECKLE_LEGACY_UI]
if vue_view
vue_view.dialog.reset_dialog_location
else
puts "Speckle UI didn't initialized!"
end
end
end
end
end
@@ -9,7 +9,7 @@ module SpeckleConnector
module Commands
# Command to saved stream.
class SaveStream < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
app.update_state!(Actions::SaveStream.new(stream_id))
end
@@ -7,7 +7,7 @@ module SpeckleConnector
module Commands
# Command to send selection to Speckle Server.
class SendSelection < Command
def _run(data)
def _run(_resolve_id, data)
stream_id = data['stream_id']
action = Actions::SendSelection.new(stream_id)
app.update_state!(action)
@@ -3,13 +3,16 @@
require_relative 'menu_command_handler'
require_relative 'action_command'
require_relative 'initialize_speckle'
require_relative '../actions/one_click_send'
require_relative 'reset_window_location'
require_relative 'initialize_dui3_speckle'
module SpeckleConnector
module Commands
# Speckle menu commands that adds them to Sketchup menu and toolbar.
class SpeckleMenuCommands
CMD_INITIALIZE_SPECKLE = :initialize_speckle
CMD_RESET_WINDOW_LOCATION_SPECKLE = :reset_window_location_speckle
CMD_INITIALIZE_DUI3_SPECKLE = :initialize_dui3_speckle
CMD_SEND_TO_SPECKLE = :send_to_speckle
CMD_RECEIVE_FROM_SPECKLE = :receive_from_speckle
@@ -22,9 +25,16 @@ module SpeckleConnector
speckle_menu = sketchup_ui.speckle_menu
speckle_toolbar = sketchup_ui.speckle_toolbar
commands[CMD_INITIALIZE_SPECKLE] = initialize_speckle_command(app)
commands.add_to_menu!(CMD_INITIALIZE_SPECKLE, speckle_menu)
commands.add_to_toolbar!(CMD_INITIALIZE_SPECKLE, speckle_toolbar)
# commands[CMD_INITIALIZE_SPECKLE] = initialize_speckle_command(app)
# commands.add_to_menu!(CMD_INITIALIZE_SPECKLE, speckle_menu)
# commands.add_to_toolbar!(CMD_INITIALIZE_SPECKLE, speckle_toolbar)
commands[CMD_RESET_WINDOW_LOCATION_SPECKLE] = reset_window_location_command(app)
commands.add_to_menu!(CMD_RESET_WINDOW_LOCATION_SPECKLE, speckle_menu)
commands[CMD_INITIALIZE_DUI3_SPECKLE] = initialize_dui3_speckle_command(app)
commands.add_to_menu!(CMD_INITIALIZE_DUI3_SPECKLE, speckle_menu)
commands.add_to_toolbar!(CMD_INITIALIZE_DUI3_SPECKLE, speckle_toolbar)
# commands[CMD_SEND_TO_SPECKLE] = send_command(app)
# commands.add_to_menu!(CMD_SEND_TO_SPECKLE, speckle_menu)
@@ -33,7 +43,7 @@ module SpeckleConnector
def self.initialize_speckle_command(app)
cmd = MenuCommandHandler.sketchup_command(
InitializeSpeckle.new(app), 'Initialize Speckle'
InitializeSpeckle.new(app, nil), 'Initialize Speckle'
)
cmd.tooltip = 'Launch Connector'
cmd.status_bar_text = 'Opens the Speckle Connector window'
@@ -42,9 +52,31 @@ module SpeckleConnector
cmd
end
def self.reset_window_location_command(app)
cmd = MenuCommandHandler.sketchup_command(
ResetWindowLocation.new(app, nil), 'Reset Window Location'
)
cmd.tooltip = 'Bring Speckle window onto center of SketchUp window'
cmd.status_bar_text = 'Bring Speckle window onto center of SketchUp window'
cmd.small_icon = '../../img/s2logo.png'
cmd.large_icon = '../../img/s2logo.png'
cmd
end
def self.initialize_dui3_speckle_command(app)
cmd = MenuCommandHandler.sketchup_command(
InitializeDUI3Speckle.new(app, nil), 'Initialize Speckle with New UI'
)
cmd.tooltip = 'Launch Connector with New UI'
cmd.status_bar_text = 'Opens the Speckle Connector with New UI'
cmd.small_icon = '../../img/s2logo_dui3.png'
cmd.large_icon = '../../img/s2logo_dui3.png'
cmd
end
def self.send_command(app)
cmd = MenuCommandHandler.sketchup_command(
ActionCommand.new(app, Actions::OneClickSend), 'Send to Speckle'
ActionCommand.new(app, nil, Actions::OneClickSend), 'Send to Speckle'
)
cmd.tooltip = 'Send to Speckle'
cmd.status_bar_text = 'Send to Speckle'
@@ -8,7 +8,7 @@ module SpeckleConnector
module Commands
# Command to update preferences.
class UserPreferencesUpdated < Command
def _run(data)
def _run(_resolve_id, data)
preference_hash = data['preference_hash']
preference = data['preference']
new_value = data['value']
@@ -5,6 +5,9 @@ module SpeckleConnector
SPECKLE_MAPPING_TOOL_SCHEMA = 'Speckle_Mapping_Tool_Schema'
SPECKLE_SCHEMA = 'Speckle_Schema'
SPECKLE_SEND_CARDS = 'Speckle_Send_Cards'
SPECKLE_RECEIVE_CARDS = 'Speckle_Receive_Cards'
SPECKLE_ID = 'speckle_id'
SPECKLE_TYPE = 'speckle_type'
APPLICATION_ID = 'application_id'
@@ -3,6 +3,7 @@
module SpeckleConnector
APP_OBSERVER = 'SpeckleConnector::Observers::AppObserver'
ENTITIES_OBSERVER = 'SpeckleConnector::Observers::EntitiesObserver'
ENTITY_OBSERVER = 'SpeckleConnector::Observers::EntityObserver'
MODEL_OBSERVER = 'SpeckleConnector::Observers::ModelObserver'
SELECTION_OBSERVER = 'SpeckleConnector::Observers::SelectionObserver'
end
@@ -15,7 +15,7 @@ module SpeckleConnector
Sketchup::ComponentInstance => INCLUDE_COMPONENT_ENTITY_ATTRIBUTES,
Sketchup::Group => INCLUDE_GROUP_ENTITY_ATTRIBUTES,
Sketchup::Face => INCLUDE_FACE_ENTITY_ATTRIBUTES,
Sketchup::Face => INCLUDE_EDGE_ENTITY_ATTRIBUTES
Sketchup::Edge => INCLUDE_EDGE_ENTITY_ATTRIBUTES
}.freeze
LEVEL_SHIFT_VALUE = SpeckleObjects::Geometry.length_to_native(1.5, 'm')
@@ -4,6 +4,7 @@ module SpeckleConnector
BASE_OBJECT = 'Base'
OBJECTS_GIS_POLYGONELEMENT = 'Objects.GIS.PolygonElement'
OBJECTS_GIS_LINEELEMENT = 'Objects.GIS.LineElement'
OBJECTS_BUILTELEMENTS_VIEW3D = 'Objects.BuiltElements.View:Objects.BuiltElements.View3D'
OBJECTS_BUILTELEMENTS_NETWORK = 'Objects.BuiltElements.Network'
@@ -12,9 +13,19 @@ module SpeckleConnector
OBJECTS_BUILTELEMENTS_REVIT_FLOOR = 'Objects.BuiltElements.Floor:Objects.BuiltElements.Revit.RevitFloor'
OBJECTS_BUILTELEMENTS_DEFAULT_WALL = 'Objects.BuiltElements.Wall'
OBJECTS_BUILTELEMENTS_REVIT_WALL = 'Objects.BuiltElements.Wall:Objects.BuiltElements.Revit.RevitWall'
OBJECTS_BUILTELEMENTS_DEFAULT_COLUMN = 'Objects.BuiltElements.Column'
OBJECTS_BUILTELEMENTS_REVIT_COLUMN = 'Objects.BuiltElements.Column:Objects.BuiltElements.Revit.RevitColumn'
OBJECTS_BUILTELEMENTS_DEFAULT_BEAM = 'Objects.BuiltElements.Beam'
OBJECTS_BUILTELEMENTS_REVIT_BEAM = 'Objects.BuiltElements.Beam:Objects.BuiltElements.Revit.RevitBeam'
OBJECTS_BUILTELEMENTS_DEFAULT_PIPE = 'Objects.BuiltElements.Pipe'
OBJECTS_BUILTELEMENTS_REVIT_PIPE = 'Objects.BuiltElements.Pipe:Objects.BuiltElements.Revit.RevitPipe'
OBJECTS_BUILTELEMENTS_DEFAULT_DUCT = 'Objects.BuiltElements.Duct'
OBJECTS_BUILTELEMENTS_REVIT_DUCT = 'Objects.BuiltElements.Duct:Objects.BuiltElements.Revit.RevitDuct'
OBJECTS_BUILTELEMENTS_REVIT_DIRECTSHAPE = 'Objects.BuiltElements.Revit.DirectShape'
OBJECTS_BUILTELEMENTS_REVIT_FAMILY_INSTANCE = 'Objects.BuiltElements.Revit.FamilyInstance'
OBJECTS_BUILTELEMENTS_REVIT_PARAMETER = 'Objects.BuiltElements.Revit.Parameter'
OBJECTS_BUILTELEMENTS_REVIT_REVITELEMENTTYPE = 'Objects.BuiltElements.Revit.RevitElementType'
OBJECTS_BUILTELEMENTS_REVIT_REVITSYMBOLELEMENTTYPE = 'Objects.BuiltElements.Revit.RevitElementType:Objects.BuiltElements.Revit.RevitSymbolElementType'
OBJECTS_GEOMETRY_LINE = 'Objects.Geometry.Line'
OBJECTS_GEOMETRY_POLYLINE = 'Objects.Geometry.Polyline'
@@ -32,5 +43,9 @@ module SpeckleConnector
OBJECTS_OTHER_RENDERMATERIAL = 'Objects.Other.RenderMaterial'
OBJECTS_OTHER_DISPLAYSTYLE = 'Objects.Other.DisplayStyle'
SPECKLE_CORE_MODELS_COLLECTION = 'Speckle.Core.Models.Collection'
SPECKLE_CORE_MODELS_COLLECTION = 'Speckle.Core.Models.Collections.Collection'
SPECKLE_CORE_MODELS_INSTANCES_INSTANCE_PROXY = 'Speckle.Core.Models.Instances.InstanceProxy'
SPECKLE_CORE_MODELS_INSTANCES_INSTANCE_DEFINITION_PROXY = 'Speckle.Core.Models.Instances.InstanceDefinitionProxy'
SPECKLE_CORE_MODELS_COLLECTION_RASTER_LAYER = 'Speckle.Core.Models.Collection:Objects.GIS.RasterLayer'
SPECKLE_CORE_MODELS_COLLECTION_VECTOR_LAYER = 'Speckle.Core.Models.Collection:Objects.GIS.VectorLayer'
end
@@ -5,6 +5,8 @@ require 'securerandom'
# rubocop:enable SketchupPerformance/OpenSSL
require 'digest'
require_relative 'converter'
require_relative '../speckle_objects/base'
require_relative '../speckle_objects/object_reference'
require_relative '../speckle_entities/speckle_entity'
require_relative '../relations/many_to_one_relation'
@@ -16,23 +18,17 @@ module SpeckleConnector
# @return [Integer] default chunk size the determine splitting base prop into chucks
attr_reader :default_chunk_size
# @return [String] stream id to send conversion
attr_reader :stream_id
attr_reader :object_references
attr_accessor :speckle_state
# @param stream_id [String] stream id to send conversion
def initialize(speckle_state, stream_id, preferences, default_chunk_size = 1000)
@speckle_state = speckle_state
@stream_id = stream_id
def initialize(preferences, default_chunk_size = 1000)
@preferences = preferences
@default_chunk_size = default_chunk_size
@detach_lineage = []
@lineage = []
@family_tree = {}
@family_tree_relation = Relations::ManyToOneRelation.new
@closure_table = {}
@objects = {}
@object_references = {}
end
# @param base [Object] top base object to populate all children and their relationship
@@ -47,36 +43,15 @@ module SpeckleConnector
@objects[id][:totalChildrenCount]
end
# @param base_and_entities [Object] base object to populate all children and their relationship
# @param base [Object] base object to populate all children and their relationship
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/AbcSize
def traverse_base(base_and_entities)
base, entities = base_and_entities
def traverse_base(base)
# 1. Create random string for lineage tracking.
@lineage.append(SecureRandom.hex)
# 2. Get last item from detach_lineage array
is_detached = @detach_lineage.pop
# unless entities.nil?
# is_sent_before = entities.all? do |entity|
# check_base_available_on_state(entity, speckle_state)
# end
# if is_sent_before
# speckle_entity = speckle_state.speckle_entities[entities.first.persistent_id]
# ref_object = detach_helper(speckle_entity.id)
# parent = @lineage[-1]
# unless @family_tree[parent].nil?
# @family_tree[parent] = @family_tree[parent].merge(speckle_entity.speckle_object[:__closure])
# end
# @objects[speckle_entity.id] = ref_object if is_detached
# return speckle_entity.id, ref_object
# end
# end
# 3. Initialize traversed base object that will be filled with traversed values or
# traversed base objects as props.
traversed_base = SpeckleObjects::Base.new(speckle_type: base[:speckle_type], id: '')
@@ -85,7 +60,6 @@ module SpeckleConnector
traversed_base.delete(:applicationId)
# 4. Iterate all entries (key, value) of the base {Base > Hash} object
# speckle_state = traverse_base_props(base, traversed_base)
traverse_base_props(base, traversed_base)
# this is where all props are done for current `traversed_base`
@@ -116,19 +90,15 @@ module SpeckleConnector
# 10. Save object string if detached
@objects[id] = traversed_base if is_detached
if @preferences[:user][:register_speckle_entity] && !entities.nil?
entities.uniq.each do |entity|
speckle_entity = create_or_update_speckle_entity(entity, id, traversed_base)
@speckle_state = speckle_state.with_speckle_entity(speckle_entity)
end
if traversed_base[:applicationId]
@object_references[traversed_base[:applicationId].to_s] = SpeckleObjects::ObjectReference.new(
id, traversed_base[:applicationId].to_s, traversed_base[:__closure]
)
end
return id, traversed_base
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
@@ -155,7 +125,7 @@ module SpeckleConnector
chunked_detach_match = prop.match(/^@\((\d*)\)/)
# 3.5. If split chunk is needed and prop value is array, then run chunking process
if value.is_a?(Array) && !base_and_entities?(value) && chunked_detach_match
if value.is_a?(Array) && chunked_detach_match
# 3.5.1. Determine chunk size, get it from prop if defined. ex: '@(31250)faces' -> 31250 = chunk size
chunk_size = chunked_detach_match[1] == '' ? default_chunk_size : chunked_detach_match[1].to_i
@@ -204,12 +174,15 @@ module SpeckleConnector
child = traverse_value(value, is_detach_prop)
is_base = (value.is_a?(Hash) && !value[:speckle_type].nil?) ||
(base_and_entities?(value) && value[0].is_a?(Hash) && !value[0][:speckle_type].nil?)
is_base = value.is_a?(Hash) && !value[:speckle_type].nil?
# 3.6. traverse value according to value is a speckle object or not
traversed_base[prop] = if is_base
is_detach_prop ? detach_helper(child[:id]) : child
if child[:referencedId] && child[:speckle_type] == 'reference'
is_detach_prop ? detach_helper(child[:referencedId]) : child
else
is_detach_prop ? detach_helper(child[:id]) : child
end
else
child
end
@@ -221,18 +194,6 @@ module SpeckleConnector
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/PerceivedComplexity
# Whether value has a pattern [<converted>, [<entity>, <entity>, ... <entity>]] or not.
def base_and_entities?(value)
is_array = value.is_a?(Array)
return false unless is_array
return false unless is_array && value.length == 2
return false if value[1].nil?
value[1].all? { |v| v.is_a?(Sketchup::Entity) }
end
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
@@ -242,8 +203,8 @@ module SpeckleConnector
# 1. Return same value if value is primitive type (string, numeric, boolean)
return value unless value.is_a?(Hash) || value.is_a?(Array)
# 2. For pure arrays (Without referencing any Sketchup Entity)
if value.is_a?(Array) && !base_and_entities?(value)
# 2. For pure arrays
if value.is_a?(Array)
# 2.1. If it is not detached then iterate array by traversing with their value
unless is_detach
@@ -257,7 +218,17 @@ module SpeckleConnector
# 2.2. If it is detached than collect them into detached_list
detached_list = []
value.each do |el|
if (el.is_a?(Hash) && !el[:speckle_type].nil?) || base_and_entities?(el)
if el.is_a?(SpeckleObjects::ObjectReference)
if el.closure
el.closure.each_key do |k|
detach_helper(k)
end
end
detached_list.append(detach_helper(el.referenced_id))
next
end
if el.is_a?(Hash) && !el[:speckle_type].nil?
@detach_lineage.append(is_detach)
id, _traversed_base = traverse_base(el)
detached_list.append(detach_helper(id))
@@ -269,11 +240,21 @@ module SpeckleConnector
return detached_list
end
# 3. Hash
# 3. ObjectReference
if value.is_a?(SpeckleObjects::ObjectReference)
if value.closure
value.closure.each_key do |k|
detach_helper(k)
end
end
return detach_helper(value.referenced_id)
end
# 4. Hash
return value if value.is_a?(Hash) && value[:speckle_type].nil?
# 4. Base objects
if (value.is_a?(Hash) && !value[:speckle_type].nil?) || base_and_entities?(value)
# 5. Base objects
if value.is_a?(Hash) && !value[:speckle_type].nil?
@detach_lineage.append(is_detach)
_id, traversed_base = traverse_base(value)
return traversed_base
@@ -310,8 +291,12 @@ module SpeckleConnector
Digest::MD5.hexdigest(traversed_base.to_json)
end
def batch_objects
@objects
end
# rubocop:disable Metrics/MethodLength
def batch_objects(max_batch_size_mb = 1)
def batch_json_objects(max_batch_size_mb = 1)
max_size = 1000 * 1000 * max_batch_size_mb
batches = []
batch = '['
@@ -335,32 +320,6 @@ module SpeckleConnector
batches
end
# rubocop:enable Metrics/MethodLength
# @param entity [Sketchup::Entity] source entity object
# @param speckle_state [States::SpeckleState] the current speckle state of the {States::State}
def check_base_available_on_state(entity, speckle_state)
is_exist = speckle_state.speckle_entities.keys.include?(entity.persistent_id)
return is_exist unless is_exist
speckle_state.speckle_entities[entity.persistent_id].valid_stream_ids.include?(stream_id)
end
# Creates or updates speckle entity.
# If speckle entity exist in state, creates new one by updating old one.
# Else creates new one
# @return [SpeckleEntity] speckle entity that collects both speckle and sketchup information.
def create_or_update_speckle_entity(entity, id, traversed_base)
if speckle_state.speckle_entities.keys.include?(entity.persistent_id)
speckle_state.speckle_entities[entity.persistent_id].with_valid_stream_id(stream_id)
else
children = traversed_base[:__closure].nil? ? {} : traversed_base[:__closure]
speckle_entity = SpeckleEntities::SpeckleEntity.new(entity, id, entity.persistent_id,
traversed_base[:speckle_type],
children.keys, [stream_id])
speckle_entity.write_initial_base_data
speckle_entity
end
end
end
end
end
@@ -0,0 +1,268 @@
# frozen_string_literal: true
# rubocop:disable SketchupPerformance/OpenSSL
require 'securerandom'
# rubocop:enable SketchupPerformance/OpenSSL
require 'digest'
require_relative 'converter'
require_relative '../relations/many_to_one_relation'
module SpeckleConnector
module Converters
# Serializer of the base object.
# Responsible to create id (hash) of the objects by holding their lineage and detaching relationships.
class BaseObjectSerializerV2
# @return [Integer] default chunk size the determine splitting base prop into chucks
attr_reader :default_chunk_size
def initialize(default_chunk_size = 1000)
@default_chunk_size = default_chunk_size
@detach_lineage = []
@lineage = []
@family_tree = {}
@family_tree_relation = Relations::ManyToOneRelation.new
@closure_table = {}
@objects = {}
end
# @param base [Object] top base object to populate all children and their relationship
# @return [String, String] id (hash) and traversed hash
def serialize(base)
id, traversed = traverse_base(base)
@objects[id] = traversed
return id, traversed
end
def total_children_count(id)
@objects[id][:totalChildrenCount]
end
# @param base [Object] base object to populate all children and their relationship
# rubocop:disable Metrics/MethodLength
def traverse_base(base)
# 1. Create random string for lineage tracking.
@lineage.append(SecureRandom.hex)
# 2. Initialize traversed base object that will be filled with traversed values or
# traversed base objects as props.
traversed_base = SpeckleObjects::Base.new(speckle_type: base[:speckle_type], id: '')
traversed_base.delete(:applicationId)
# 3. Iterate all entries (key, value) of the base {Base > Hash} object
traverse_base_props(base, traversed_base)
# this is where all props are done for current `traversed_base`
# 4. Get last item from detach_lineage array
is_detached = @detach_lineage.pop
# 5. Add closures
closure = {}
parent = @lineage.pop
unless @family_tree[parent].nil?
@family_tree[parent].each do |ref, depth|
closure[ref] = depth - @detach_lineage.length
end
end
# 6. Add total children count
traversed_base[:totalChildrenCount] = closure.keys.length
# 7. Finally create id
id = get_id(traversed_base)
# 8. Add id to traversed base
traversed_base[:id] = id
# 9. Update __closure table on the traversed base
unless traversed_base[:totalChildrenCount].nil?
@closure_table[id] = closure
traversed_base[:__closure] = closure unless closure.empty?
end
# 10. Save object string if detached
@objects[id] = traversed_base if is_detached
return id, traversed_base
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/BlockLength
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
def traverse_base_props(base, traversed_base)
base.each do |prop, value|
# 3.1. Ignore nil, starts with '_' and 'id'
next if value.nil? || prop[0] == '_' || prop == 'id' || prop == :id
# 3.2. Pass primitives without any operation (string, numeric, boolean)
unless value.is_a?(Hash) || value.is_a?(Array)
traversed_base[prop] = value
next
end
# 3.3. Determine prop is detached or not
is_prop_detach = prop[0] == '@'
# 3.4. Check prop needs to split into chunks
chunked_detach_match = prop.match(/^@\((\d*)\)/)
# 3.5. If split chunk is needed and prop value is array, then run chunking process
if value.is_a?(Array) && chunked_detach_match
# 3.5.1. Determine chunk size, get it from prop if defined. ex: '@(31250)faces' -> 31250 = chunk size
chunk_size = chunked_detach_match[1] == '' ? default_chunk_size : chunked_detach_match[1].to_i
# 3.5.2. Init empty array for chunks
chunks = []
# 3.5.3. Init empty data chunk core object
chunk = {
speckle_type: 'Speckle.Core.Models.DataChunk',
data: []
}
# 3.5.4. Iterate each element on array to fill them into chunks
value.each_with_index do |el, index|
# 3.5.4.1. If current index is the multiplier of the chunk size, then need to append chunk into chunks
# and reinitialize empty chunk for next batch
if (index % chunk_size == 0) && index != 0
chunks.append(chunk)
chunk = {
speckle_type: 'Speckle.Core.Models.DataChunk',
data: []
}
end
# 3.5.4.2. Add element into chunk
chunk[:data].append(el)
end
# 3.5.5. Add trailing batch to the chunks also unless is empty
chunks.append(chunk) unless chunk[:data].empty?
# 3.5.6. Initialize empty chunk reference array
chunk_references = []
chunks.each do |chunk_element|
@detach_lineage.append(is_prop_detach)
id, _traversed = traverse_base(chunk_element)
chunk_references.append(detach_helper(id))
end
# 3.5.7. Add chunk references to the traversed base prop without @(<chunk_size>)
traversed_base[prop.to_s.sub(chunked_detach_match[0], '')] = chunk_references
# 3.5.8. We are done chunking, good to go next
next
end
# 3.6. traverse value according to value is a speckle object or not
if value.is_a?(Hash) && !value[:speckle_type].nil?
child = traverse_value(value, is_prop_detach)
traversed_base[prop] = is_prop_detach ? detach_helper(child[:id]) : child
else
traversed_base[prop] = traverse_value(value, is_prop_detach)
end
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/BlockLength
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Style/OptionalBooleanParameter
def traverse_value(value, is_detach = false)
# 1. Return same value if value is primitive type (string, numeric, boolean)
return value unless value.is_a?(Hash) || value.is_a?(Array)
# 2. Arrays
if value.is_a?(Array)
# 2.1. If it is not detached then iterate array by traversing with their value
return value.collect { |el| traverse_value(el) } unless is_detach
# 2.2. If it is detached than collect them into detached_list
detached_list = []
value.each do |el|
if (el.is_a?(Array) || el.is_a?(Hash)) && !el[:speckle_type].nil?
@detach_lineage.append(is_detach)
id, _traversed_base = traverse_base(el)
detached_list.append(detach_helper(id))
else
detached_list.append(traverse_value(el, is_detach))
end
end
return detached_list
end
# 3. Hash
return value if value[:speckle_type].nil?
# 4. Base objects
unless value[:speckle_type].nil?
@detach_lineage.append(is_detach)
_id, traversed_base = traverse_base(value)
return traversed_base
end
# 5. If it is not returned until here then there is unsupported type
raise StandardError "Unsupported type #{value.class} : #{value}"
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:enable Style/OptionalBooleanParameter
def detach_helper(reference_id)
@lineage.each do |parent|
# init parent on the family tree unless exist
@family_tree[parent] = {} if @family_tree[parent].nil?
is_ref_exist = !@family_tree[parent].nil? && !@family_tree[parent][reference_id].nil?
if !is_ref_exist || @family_tree[parent][reference_id] > @detach_lineage.length
@family_tree[parent][reference_id] = @detach_lineage.length
end
end
{
referencedId: reference_id,
speckle_type: 'reference'
}
end
# @param traversed_base [SpeckleConnector::SpeckleObjects::Base] traversed base object.
def get_id(traversed_base)
Digest::MD5.hexdigest(traversed_base.to_json)
end
# rubocop:disable Metrics/MethodLength
def batch_objects(max_batch_size_mb = 1)
max_size = 1000 * 1000 * max_batch_size_mb
batches = []
batch = '['
batch_size = 0
objects = @objects.values
objects.each do |obj|
obj_json = obj.to_json
if batch_size + obj_json.length < max_size
batch += obj_json
batch += ','
batch_size += obj_json.length
else
batch = batch.chop
batches.append("#{batch}]")
batch = "[#{obj_json},"
batch_size = obj_json.length
end
end
batch = batch.chop
batches.append("#{batch}]")
batches
end
# rubocop:enable Metrics/MethodLength
end
end
end
+14 -9
View File
@@ -61,19 +61,24 @@ module SpeckleConnector
face_1, face_2 = edge.faces
return false unless face_1.normal.samedirection?(face_2.normal)
begin
return false unless face_1.normal.samedirection?(face_2.normal)
return false if face_duplicate?(face_1, face_2)
# Check for troublesome faces which might lead to missing geometry if merged.
return false unless edge_safe_to_merge?(edge)
return false if face_duplicate?(face_1, face_2)
# Check for troublesome faces which might lead to missing geometry if merged.
return false unless edge_safe_to_merge?(edge)
return false unless (face_1.material == face_2.material) && (face_1.back_material == face_2.back_material)
return false unless (face_1.material == face_2.material) && (face_1.back_material == face_2.back_material)
# Check faces are coplanar or not.
return false unless faces_coplanar?(face_1, face_2)
# Check faces are coplanar or not.
return false unless faces_coplanar?(face_1, face_2)
edge.erase!
true
edge.erase!
true
rescue StandardError => e
puts "Failed to merge coplanar faces by removing edge with error: #{e}"
false
end
end
# Determines if two faces are overlapped.
@@ -28,7 +28,7 @@ module SpeckleConnector
@sketchup_model = state.sketchup_state.sketchup_model
@stream_id = stream_id
su_unit = state.sketchup_state.length_units
@units = Converters::SKETCHUP_UNITS[su_unit]
@units = Converters::SKETCHUP_UNITS[su_unit]
@definitions = {}
end
end
@@ -0,0 +1,41 @@
# frozen_string_literal: true
module SpeckleConnector
module Converters
# Helper class to convert geometries between server and Sketchup.
class ConverterV2
# @return [States::State] the current state of the {SpeckleConnector::App}
attr_reader :state
# @return [States::SpeckleState] the current speckle state of the {States::State}
attr_reader :speckle_state
# @return [Sketchup::Model] active sketchup model.
attr_reader :sketchup_model
# @return [Cards::Card] card that conversion happening with it
attr_reader :model_card
# @return [String] speckle units
attr_reader :units
# @return [String] prefix that structured from Project and Model name
attr_reader :model_prefix
attr_accessor :definitions
# @param state [States::State] the current state of the {SpeckleConnector::App}
# @param model_card [Cards::Card] model card that holds info for operation
def initialize(state, model_card)
@state = state
@model_card = model_card
@model_prefix = "Project: #{model_card.project_name} Model: #{model_card.model_name}"
@speckle_state = state.speckle_state
@sketchup_model = state.sketchup_state.sketchup_model
su_unit = state.sketchup_state.length_units
@units = Converters::SKETCHUP_UNITS[su_unit]
@definitions = {}
end
end
end
end
+37 -3
View File
@@ -4,6 +4,7 @@ require_relative 'converter'
require_relative '../constants/type_constants'
require_relative '../speckle_entities/speckle_entity'
require_relative '../speckle_objects/gis/polygon_element'
require_relative '../speckle_objects/gis/line_element'
require_relative '../speckle_objects/other/transform'
require_relative '../speckle_objects/other/render_material'
require_relative '../speckle_objects/other/block_definition'
@@ -19,7 +20,9 @@ require_relative '../speckle_objects/geometry/mesh'
require_relative '../speckle_objects/built_elements/view3d'
require_relative '../speckle_objects/built_elements/network'
require_relative '../speckle_objects/speckle/core/models/collection'
require_relative '../speckle_objects/speckle/core/models/gis_layer_collection'
require_relative '../sketchup_model/dictionary/speckle_entity_dictionary_handler'
require_relative '../ui_data/report/conversion_result'
module SpeckleConnector
module Converters
@@ -34,12 +37,18 @@ module SpeckleConnector
attr_reader :converted_faces
def initialize(state, stream_id, stream_name, branch_name, source_app)
super(state, stream_id)
attr_reader :converted_entities
attr_reader :conversion_results
def initialize(state, stream_id, stream_name, branch_name, source_app, model_card_id)
super(state, stream_id, model_card_id)
@stream_name = stream_name
@branch_name = branch_name
@source_app = source_app.downcase
@converted_faces = []
@converted_entities = []
@conversion_results = []
end
# Module aliases
@@ -64,7 +73,9 @@ module SpeckleConnector
DISPLAY_VALUE = OTHER::DisplayValue
VIEW3D = BUILTELEMENTS::View3d
POLYGON_ELEMENT = GIS::PolygonElement
LINE_ELEMENT = GIS::LineElement
COLLECTION = SpeckleObjects::Speckle::Core::Models::Collection
GIS_LAYER_COLLECTION = SpeckleObjects::Speckle::Core::Models::GisLayerCollection
BASE_OBJECT_PROPS = %w[applicationId id speckle_type totalChildrenCount].freeze
CONVERTABLE_SPECKLE_TYPES = %w[
@@ -84,7 +95,10 @@ module SpeckleConnector
Objects.BuiltElements.Wall:Objects.BuiltElements.Revit.RevitWall
Objects.BuiltElements.Network
Objects.GIS.PolygonElement
Objects.GIS.LineElement
Speckle.Core.Models.Collection
Speckle.Core.Models.Collection:Objects.GIS.RasterLayer
Speckle.Core.Models.Collection:Objects.GIS.VectorLayer
].freeze
def from_revit
@@ -139,6 +153,7 @@ module SpeckleConnector
def try_create_instance
if !from_sketchup && (!@is_update_commit || @branch_definition.instances.empty?)
instance = sketchup_model.entities.add_instance(@branch_definition, Geom::Transformation.new)
@converted_entities.append(instance)
BLOCK_INSTANCE.align_instance_axes(instance) if from_qgis
end
end
@@ -303,7 +318,10 @@ module SpeckleConnector
OBJECTS_BUILTELEMENTS_REVIT_DIRECTSHAPE => BUILTELEMENTS::Revit::DirectShape.method(:to_native),
OBJECTS_BUILTELEMENTS_NETWORK => BUILTELEMENTS::Network.method(:to_native),
OBJECTS_GIS_POLYGONELEMENT => POLYGON_ELEMENT.method(:to_native),
SPECKLE_CORE_MODELS_COLLECTION => COLLECTION.method(:to_native)
OBJECTS_GIS_LINEELEMENT => LINE_ELEMENT.method(:to_native),
SPECKLE_CORE_MODELS_COLLECTION => COLLECTION.method(:to_native),
SPECKLE_CORE_MODELS_COLLECTION_RASTER_LAYER => GIS_LAYER_COLLECTION.method(:to_native),
SPECKLE_CORE_MODELS_COLLECTION_VECTOR_LAYER => GIS_LAYER_COLLECTION.method(:to_native)
}.freeze
# @param state [States::State] state of the speckle application
@@ -315,6 +333,7 @@ module SpeckleConnector
# Call 'to_native' method by passing this method itself to handle nested 'to_native' conversions.
# It returns updated state and converted entities.
state, converted_entities = to_native_method.call(state, obj, layer, entities, &convert_to_native)
@converted_entities += converted_entities
faces = converted_entities.select { |e| e.is_a?(Sketchup::Face) }
@converted_faces += faces if faces.any?
if from_revit
@@ -324,10 +343,25 @@ module SpeckleConnector
create_layers_from_categories(state, obj, converted_entities)
end
# Create speckle entities from sketchup entities to achieve continuous traversal.
converted_entities.each do |converted|
@conversion_results.push(UiData::Report::ConversionResult.new(UiData::Report::ConversionStatus::SUCCESS,
obj['id'],
obj['speckle_type'],
converted.persistent_id,
converted.class))
end
SpeckleEntities::SpeckleEntity.from_speckle_object(state, obj, converted_entities, stream_id)
rescue StandardError => e
puts("Failed to convert #{obj['speckle_type']} (id: #{obj['id']})")
puts(e)
@conversion_results.push(UiData::Report::ConversionResult.new(UiData::Report::ConversionStatus::ERROR,
obj['id'],
obj['speckle_type'],
nil,
nil,
e))
return state, []
end

Some files were not shown because too many files have changed in this diff Show More