App_Main.py 448 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from AppObjects.ObjectCollection import *
  50. from AppObjects.FlatCAMObj import FlatCAMObj
  51. from AppObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from AppParsers.ParseExcellon import Excellon
  54. from AppParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM AppGUI
  57. from AppGUI.PlotCanvas import *
  58. from AppGUI.PlotCanvasLegacy import *
  59. from AppGUI.MainGUI import *
  60. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from AppPreProcessor import load_preprocessors
  63. # FlatCAM AppEditors
  64. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from AppEditors.FlatCAMTextEditor import TextEditor
  68. from AppParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from AppProcess import *
  71. from AppWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from AppTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import AppTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal(str)
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  699. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  700. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  701. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  702. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  703. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  704. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  705. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  706. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  707. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  708. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  709. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  710. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  711. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  712. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  713. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  714. # ToolBar signals
  715. self.connect_toolbar_signals()
  716. # Notebook and Plot Tab Area signals
  717. # make the right click on the notebook tab and plot tab area tab raise a menu
  718. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.on_tab_setup_context_menu()
  721. # activate initial state
  722. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  723. # Context Menu
  724. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  725. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  726. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  727. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  728. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  729. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  730. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  731. self.ui.clearplot.triggered.connect(self.clear_plots)
  732. self.ui.replot.triggered.connect(self.plot_all)
  733. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  734. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  735. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  736. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  737. self.ui.popmenu_move.triggered.connect(self.obj_move)
  738. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  739. # Project Context Menu -> Color Setting
  740. for act in self.ui.menuprojectcolor.actions():
  741. act.triggered.connect(self.on_set_color_action_triggered)
  742. # ###########################################################################################################
  743. # #################################### GUI PREFERENCES SIGNALS ##############################################
  744. # ###########################################################################################################
  745. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  746. lambda: self.on_toggle_units(no_pref=False))
  747. # ##################################### Workspace Setting Signals ###########################################
  748. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  749. self.on_workspace_modified)
  750. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  751. self.on_workspace_modified
  752. )
  753. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  754. # ###########################################################################################################
  755. # ######################################## GUI SETTINGS SIGNALS #############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  758. # ######################################## Tools related signals ############################################
  759. # portability changed signal
  760. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  761. # Object list
  762. self.object_status_changed.connect(self.collection.on_collection_updated)
  763. # when there are arguments at application startup this get launched
  764. self.args_at_startup[list].connect(self.on_startup_args)
  765. # ###########################################################################################################
  766. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  767. # ###########################################################################################################
  768. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  769. lambda: self.restore_extensions(ext_type='excellon'))
  770. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  771. lambda: self.restore_extensions(ext_type='gcode'))
  772. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  773. lambda: self.restore_extensions(ext_type='gerber'))
  774. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  775. lambda: self.delete_all_extensions(ext_type='excellon'))
  776. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  777. lambda: self.delete_all_extensions(ext_type='gcode'))
  778. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  779. lambda: self.delete_all_extensions(ext_type='gerber'))
  780. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  781. lambda: self.add_extension(ext_type='excellon'))
  782. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  783. lambda: self.add_extension(ext_type='gcode'))
  784. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  785. lambda: self.add_extension(ext_type='gerber'))
  786. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  787. lambda: self.del_extension(ext_type='excellon'))
  788. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  789. lambda: self.del_extension(ext_type='gcode'))
  790. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  791. lambda: self.del_extension(ext_type='gerber'))
  792. # connect the 'Apply' buttons from the Preferences/File Associations
  793. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  794. lambda: self.on_register_files(obj_type='excellon'))
  795. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  796. lambda: self.on_register_files(obj_type='gcode'))
  797. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  798. lambda: self.on_register_files(obj_type='gerber'))
  799. # ###########################################################################################################
  800. # ########################################### KEYWORDS SIGNALS ##############################################
  801. # ###########################################################################################################
  802. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  803. lambda: self.restore_extensions(ext_type='keyword'))
  804. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  805. lambda: self.delete_all_extensions(ext_type='keyword'))
  806. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='keyword'))
  808. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='keyword'))
  810. # connect the abort_all_tasks related slots to the related signals
  811. self.proc_container.idle_flag.connect(self.app_is_idle)
  812. # signal emitted when a tab is closed in the Plot Area
  813. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  814. # signal to close the application
  815. self.close_app_signal.connect(self.kill_app)
  816. # ################################# FINISHED CONNECTING SIGNALS #############################################
  817. # ###########################################################################################################
  818. # ###########################################################################################################
  819. # ###########################################################################################################
  820. self.log.debug("Finished connecting Signals.")
  821. # ###########################################################################################################
  822. # ########################################## Other setups ###################################################
  823. # ###########################################################################################################
  824. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  825. # depending on from where those tools are called different actions can be done
  826. self.call_source = 'app'
  827. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  828. self.tool_tab_locked = False
  829. # decide if to show or hide the Notebook side of the screen at startup
  830. if self.defaults["global_project_at_startup"] is True:
  831. self.ui.splitter.setSizes([1, 1])
  832. else:
  833. self.ui.splitter.setSizes([0, 1])
  834. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  835. self.setup_component_editor()
  836. # ###########################################################################################################
  837. # ####################################### Auto-complete KEYWORDS ############################################
  838. # ###########################################################################################################
  839. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  840. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  841. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  842. 'export_exc',
  843. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  844. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  845. 'interiors', 'isolate', 'join_excellon',
  846. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  847. 'mirror', 'ncc',
  848. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  849. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  850. 'options', 'origin',
  851. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  852. 'save', 'save_project',
  853. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  854. 'skew', 'subtract_poly', 'subtract_rectangle',
  855. 'version', 'write_gcode'
  856. ]
  857. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  858. 'Paste_1',
  859. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  860. 'Toolchange_manual', 'True', 'Users',
  861. 'all', 'auto', 'axis',
  862. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  863. 'contour', 'default',
  864. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  865. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  866. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  867. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  868. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  869. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  870. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  871. 'spacing_columns',
  872. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  873. 'toolchange_xy', 'toolchangez', 'travelz',
  874. 'tooldia', 'use_threads', 'value',
  875. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  876. ]
  877. self.tcl_keywords = [
  878. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  879. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  880. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  881. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  882. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  883. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  884. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  885. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  886. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  887. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  888. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  889. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  890. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  891. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  892. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  893. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  894. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  895. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  896. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  897. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  898. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  899. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  900. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  901. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  902. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  903. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  904. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  905. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  906. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  907. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  908. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  909. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  910. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  911. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  912. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  913. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  914. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  915. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  916. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  917. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  918. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  919. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  920. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  921. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  922. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  923. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  924. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  925. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  926. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  927. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  928. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  929. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  930. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  931. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  932. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  933. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  934. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  935. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  936. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  937. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  938. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  939. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  940. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  941. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  942. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  943. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  944. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  945. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  946. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  947. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  948. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  949. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  950. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  951. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  952. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  953. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  954. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  955. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  956. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  957. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  958. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  959. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  960. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  961. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  962. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  963. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  964. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  965. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  966. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  967. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  968. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  969. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  970. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  971. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  972. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  973. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  974. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  975. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  976. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  977. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  978. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  979. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  980. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  981. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  982. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  983. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  984. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  985. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  986. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  987. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  988. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  989. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  990. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  991. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  992. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  993. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  994. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  995. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  996. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  997. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  998. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  999. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1000. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1001. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1002. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1003. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1004. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1005. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1006. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1007. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1008. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1009. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1010. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1011. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1012. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1013. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1014. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1015. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1016. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1017. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1018. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1019. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1020. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1021. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1022. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1023. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1024. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1025. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1026. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1027. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1028. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1029. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1030. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1031. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1032. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1033. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1034. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1035. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1036. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1037. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1038. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1039. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1040. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1041. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1042. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1043. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1044. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1045. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1046. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1047. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1048. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1049. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1050. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1051. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1052. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1053. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1054. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1055. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1056. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1057. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1058. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1059. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1060. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1061. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1062. ]
  1063. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1064. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1065. # ###########################################################################################################
  1066. # ############################################## Shell SETUP ################################################
  1067. # ###########################################################################################################
  1068. self.shell = FCShell(app=self, version=self.version)
  1069. self.ui.shell_dock.setWidget(self.shell)
  1070. self.log.debug("TCL Shell has been initialized.")
  1071. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1072. if self.defaults["global_shell_at_startup"]:
  1073. self.ui.shell_dock.show()
  1074. else:
  1075. self.ui.shell_dock.hide()
  1076. # ###########################################################################################################
  1077. # ########################################## Tools and Plugins ##############################################
  1078. # ###########################################################################################################
  1079. self.dblsidedtool = None
  1080. self.distance_tool = None
  1081. self.distance_min_tool = None
  1082. self.panelize_tool = None
  1083. self.film_tool = None
  1084. self.paste_tool = None
  1085. self.calculator_tool = None
  1086. self.rules_tool = None
  1087. self.sub_tool = None
  1088. self.move_tool = None
  1089. self.cutout_tool = None
  1090. self.ncclear_tool = None
  1091. self.paint_tool = None
  1092. self.isolation_tool = None
  1093. self.optimal_tool = None
  1094. self.transform_tool = None
  1095. self.properties_tool = None
  1096. self.pdf_tool = None
  1097. self.image_tool = None
  1098. self.pcb_wizard_tool = None
  1099. self.cal_exc_tool = None
  1100. self.qrcode_tool = None
  1101. self.copper_thieving_tool = None
  1102. self.fiducial_tool = None
  1103. self.edrills_tool = None
  1104. self.align_objects_tool = None
  1105. self.punch_tool = None
  1106. self.invert_tool = None
  1107. self.corners_tool = None
  1108. self.etch_tool = None
  1109. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1110. try:
  1111. self.install_tools()
  1112. except AttributeError as e:
  1113. log.debug("App.__init__() install tools() --> %s" % str(e))
  1114. # ###########################################################################################################
  1115. # ############################################ SETUP RECENT ITEMS ###########################################
  1116. # ###########################################################################################################
  1117. self.setup_recent_items()
  1118. # ###########################################################################################################
  1119. # ######################################### BookMarks Manager ###############################################
  1120. # ###########################################################################################################
  1121. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1122. self.install_bookmarks()
  1123. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1124. # ###########################################################################################################
  1125. # ########################################### Tools Database ################################################
  1126. # ###########################################################################################################
  1127. self.tools_db_tab = None
  1128. # ### System Font Parsing ###
  1129. # self.f_parse = ParseFont(self)
  1130. # self.parse_system_fonts()
  1131. # ###########################################################################################################
  1132. # ######################################### Check for updates ###############################################
  1133. # ###########################################################################################################
  1134. # Separate thread (Not worker)
  1135. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1136. if (self.beta is False or self.beta is None) and \
  1137. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1138. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1139. # self.thr2 = QtCore.QThread()
  1140. self.worker_task.emit({'fcn': self.version_check,
  1141. 'params': []})
  1142. # self.thr2.start(QtCore.QThread.LowPriority)
  1143. # ###########################################################################################################
  1144. # ##################################### Register files with FlatCAM; #######################################
  1145. # ################################### It works only for Windows for now ####################################
  1146. # ###########################################################################################################
  1147. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1148. self.on_register_files()
  1149. # ###########################################################################################################
  1150. # ######################################## Variables for global usage #######################################
  1151. # ###########################################################################################################
  1152. # hold the App units
  1153. self.units = 'MM'
  1154. # coordinates for relative position display
  1155. self.rel_point1 = (0, 0)
  1156. self.rel_point2 = (0, 0)
  1157. # variable to store coordinates
  1158. self.pos = (0, 0)
  1159. self.pos_canvas = (0, 0)
  1160. self.pos_jump = (0, 0)
  1161. # variable to store mouse coordinates
  1162. self.mouse = [0, 0]
  1163. # variable to store the delta positions on cavnas
  1164. self.dx = 0
  1165. self.dy = 0
  1166. # decide if we have a double click or single click
  1167. self.doubleclick = False
  1168. # store here the is_dragging value
  1169. self.event_is_dragging = False
  1170. # variable to store if a command is active (then the var is not None) and which one it is
  1171. self.command_active = None
  1172. # variable to store the status of moving selection action
  1173. # None value means that it's not an selection action
  1174. # True value = a selection from left to right
  1175. # False value = a selection from right to left
  1176. self.selection_type = None
  1177. # List to store the objects that are currently loaded in FlatCAM
  1178. # This list is updated on each object creation or object delete
  1179. self.all_objects_list = []
  1180. self.objects_under_the_click_list = []
  1181. # List to store the objects that are selected
  1182. self.sel_objects_list = []
  1183. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1184. self.key_modifiers = None
  1185. # Variable to hold the status of the axis
  1186. self.toggle_axis = True
  1187. # Variable to hold the status of the grid lines
  1188. self.toggle_grid_lines = True
  1189. # Variable to store the status of the code editor
  1190. self.toggle_codeeditor = False
  1191. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1192. self.click_noproject = False
  1193. self.cursor = None
  1194. # Variable to store the GCODE that was edited
  1195. self.gcode_edited = ""
  1196. self.text_editor_tab = None
  1197. # reference for the self.ui.code_editor
  1198. self.reference_code_editor = None
  1199. self.script_code = ''
  1200. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1201. self.tools_db_changed_flag = False
  1202. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1203. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1204. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1205. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1206. 'tsm']
  1207. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1208. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1209. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1210. 'sbp', 'tap', 'xpi']
  1211. self.svg_list = ['svg']
  1212. self.dxf_list = ['dxf']
  1213. self.pdf_list = ['pdf']
  1214. self.prj_list = ['flatprj']
  1215. self.conf_list = ['flatconfig']
  1216. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1217. # flag for polygons not cleared
  1218. self.poly_not_cleared = False
  1219. # VisPy visuals
  1220. self.isHovering = False
  1221. self.notHovering = True
  1222. # Window geometry
  1223. self.x_pos = None
  1224. self.y_pos = None
  1225. self.width = None
  1226. self.height = None
  1227. # when True, the app has to return from any thread
  1228. self.abort_flag = False
  1229. # set the value used in the Windows Title
  1230. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1231. # this holds a widget that is installed in the Plot Area when View Source option is used
  1232. self.source_editor_tab = None
  1233. self.pagesize = {}
  1234. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1235. # VisPy visuals
  1236. if self.is_legacy is False:
  1237. try:
  1238. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1239. except AttributeError:
  1240. self.tool_shapes = None
  1241. else:
  1242. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1243. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1244. # used in the delayed shutdown self.start_delayed_quit() method
  1245. self.save_timer = None
  1246. # ###########################################################################################################
  1247. # ################################## ADDING FlatCAM EDITORS section #########################################
  1248. # ###########################################################################################################
  1249. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1250. # at the first launch of the App , the editors will not be functional.
  1251. try:
  1252. self.geo_editor = FlatCAMGeoEditor(self)
  1253. except AttributeError:
  1254. pass
  1255. try:
  1256. self.exc_editor = FlatCAMExcEditor(self)
  1257. except AttributeError:
  1258. pass
  1259. try:
  1260. self.grb_editor = FlatCAMGrbEditor(self)
  1261. except AttributeError:
  1262. pass
  1263. self.log.debug("Finished adding FlatCAM Editor's.")
  1264. self.set_ui_title(name=_("New Project - Not saved"))
  1265. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1266. current_platform = platform.architecture()[0]
  1267. if current_platform != '64bit':
  1268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1270. # ###########################################################################################################
  1271. # ########################################### EXCLUSION AREAS ###############################################
  1272. # ###########################################################################################################
  1273. self.exc_areas = ExclusionAreas(app=self)
  1274. # ###########################################################################################################
  1275. # ##################################### Finished the CONSTRUCTOR ############################################
  1276. # ###########################################################################################################
  1277. App.log.debug("END of constructor. Releasing control.")
  1278. # ###########################################################################################################
  1279. # ########################################## SHOW GUI #######################################################
  1280. # ###########################################################################################################
  1281. # if the app is not started as headless, show it
  1282. if self.cmd_line_headless != 1:
  1283. if show_splash:
  1284. # finish the splash
  1285. self.splash.finish(self.ui)
  1286. mgui_settings = QSettings("Open Source", "FlatCAM")
  1287. if mgui_settings.contains("maximized_gui"):
  1288. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1289. if maximized_ui is True:
  1290. self.ui.showMaximized()
  1291. else:
  1292. self.ui.show()
  1293. else:
  1294. self.ui.show()
  1295. if self.defaults["global_systray_icon"]:
  1296. self.trayIcon.show()
  1297. else:
  1298. log.warning("******************* RUNNING HEADLESS *******************")
  1299. # ###########################################################################################################
  1300. # ######################################## START-UP ARGUMENTS ###############################################
  1301. # ###########################################################################################################
  1302. # test if the program was started with a script as parameter
  1303. if self.cmd_line_shellvar:
  1304. try:
  1305. cnt = 0
  1306. command_tcl = 0
  1307. for i in self.cmd_line_shellvar.split(','):
  1308. if i is not None:
  1309. # noinspection PyBroadException
  1310. try:
  1311. command_tcl = eval(i)
  1312. except Exception:
  1313. command_tcl = i
  1314. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1315. cnt += 1
  1316. # if there are Windows paths then replace the path separator with a Unix like one
  1317. if sys.platform == 'win32':
  1318. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1319. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1320. except Exception as ext:
  1321. print("ERROR: ", ext)
  1322. sys.exit(2)
  1323. if self.cmd_line_shellfile:
  1324. if self.cmd_line_headless != 1:
  1325. if self.ui.shell_dock.isHidden():
  1326. self.ui.shell_dock.show()
  1327. try:
  1328. with open(self.cmd_line_shellfile, "r") as myfile:
  1329. # if show_splash:
  1330. # self.splash.showMessage('%s: %ssec\n%s' % (
  1331. # _("Canvas initialization started.\n"
  1332. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1333. # _("Executing Tcl Script ...")),
  1334. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1335. # color=QtGui.QColor("gray"))
  1336. cmd_line_shellfile_text = myfile.read()
  1337. if self.cmd_line_headless != 1:
  1338. self.shell.exec_command(cmd_line_shellfile_text)
  1339. else:
  1340. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1341. except Exception as ext:
  1342. print("ERROR: ", ext)
  1343. sys.exit(2)
  1344. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1345. # the path/file_name must be enclosed in quotes if it contain spaces
  1346. if App.args:
  1347. self.args_at_startup.emit(App.args)
  1348. if self.defaults.old_defaults_found is True:
  1349. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1350. "Please reboot the application to update."))
  1351. self.defaults.old_defaults_found = False
  1352. # ######################################### INIT FINISHED #######################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. # #################################################################################################################
  1358. @staticmethod
  1359. def copy_and_overwrite(from_path, to_path):
  1360. """
  1361. From here:
  1362. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1363. :param from_path: source path
  1364. :param to_path: destination path
  1365. :return: None
  1366. """
  1367. if os.path.exists(to_path):
  1368. shutil.rmtree(to_path)
  1369. try:
  1370. shutil.copytree(from_path, to_path)
  1371. except FileNotFoundError:
  1372. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1373. shutil.copytree(from_new_path, to_path)
  1374. def on_startup_args(self, args, silent=False):
  1375. """
  1376. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1377. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1378. :param args: a list containing the application args at startup
  1379. :return: None
  1380. """
  1381. if args is not None:
  1382. args_to_process = args
  1383. else:
  1384. args_to_process = App.args
  1385. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1386. for argument in args_to_process:
  1387. if '.FlatPrj'.lower() in argument.lower():
  1388. try:
  1389. project_name = str(argument)
  1390. if project_name == "":
  1391. if silent is False:
  1392. self.inform.emit(_("Cancelled."))
  1393. else:
  1394. # self.open_project(project_name)
  1395. run_from_arg = True
  1396. # self.worker_task.emit({'fcn': self.open_project,
  1397. # 'params': [project_name, run_from_arg]})
  1398. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1399. except Exception as e:
  1400. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1401. elif '.FlatConfig'.lower() in argument.lower():
  1402. try:
  1403. file_name = str(argument)
  1404. if file_name == "":
  1405. if silent is False:
  1406. self.inform.emit(_("Open Config file failed."))
  1407. else:
  1408. run_from_arg = True
  1409. # self.worker_task.emit({'fcn': self.open_config_file,
  1410. # 'params': [file_name, run_from_arg]})
  1411. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1412. except Exception as e:
  1413. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1414. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1415. try:
  1416. file_name = str(argument)
  1417. if file_name == "":
  1418. if silent is False:
  1419. self.inform.emit(_("Open Script file failed."))
  1420. else:
  1421. if silent is False:
  1422. self.on_fileopenscript(name=file_name)
  1423. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1424. self.on_filerunscript(name=file_name)
  1425. except Exception as e:
  1426. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1427. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1428. log.debug("App.on_startup_args() --> Quit event.")
  1429. sys.exit()
  1430. elif 'save'.lower() in argument.lower():
  1431. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1432. self.preferencesUiManager.save_defaults()
  1433. else:
  1434. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1435. proc_arg = argument.lower()
  1436. for ext in exc_list:
  1437. proc_ext = ext.replace(' ', '')
  1438. proc_ext = '.%s' % proc_ext
  1439. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Excellon file failed."))
  1444. else:
  1445. self.on_fileopenexcellon(name=file_name, signal=None)
  1446. return
  1447. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1448. for ext in gco_list:
  1449. proc_ext = ext.replace(' ', '')
  1450. proc_ext = '.%s' % proc_ext
  1451. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open GCode file failed."))
  1456. else:
  1457. self.on_fileopengcode(name=file_name, signal=None)
  1458. return
  1459. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1460. for ext in grb_list:
  1461. proc_ext = ext.replace(' ', '')
  1462. proc_ext = '.%s' % proc_ext
  1463. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1464. file_name = str(argument)
  1465. if file_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Open Gerber file failed."))
  1468. else:
  1469. self.on_fileopengerber(name=file_name, signal=None)
  1470. return
  1471. # if it reached here without already returning then the app was registered with a file that it does not
  1472. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1473. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1474. # for arg in args_to_process:
  1475. # if 'FlatCAM.exe' in arg:
  1476. # continue
  1477. # else:
  1478. # sys.exit(2)
  1479. def set_ui_title(self, name):
  1480. """
  1481. Sets the title of the main window.
  1482. :param name: String that store the project path and project name
  1483. :return: None
  1484. """
  1485. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1486. (self.version,
  1487. ('BETA' if self.beta else ''),
  1488. platform.architecture()[0],
  1489. self.engine,
  1490. name)
  1491. )
  1492. def on_app_restart(self):
  1493. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1494. # be left in the SySTray
  1495. try:
  1496. self.trayIcon.hide()
  1497. except Exception:
  1498. pass
  1499. fcTranslate.restart_program(app=self)
  1500. def clear_pool(self):
  1501. """
  1502. Clear the multiprocessing pool and calls garbage collector.
  1503. :return: None
  1504. """
  1505. self.pool.close()
  1506. self.pool = Pool()
  1507. self.pool_recreated.emit(self.pool)
  1508. gc.collect()
  1509. def install_tools(self):
  1510. """
  1511. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1512. Instantiation of the Tools classes.
  1513. The order that the tools are installed is important as they can depend on each other install position.
  1514. :return: None
  1515. """
  1516. self.distance_tool = Distance(self)
  1517. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1518. before=self.ui.menueditorigin,
  1519. separator=False)
  1520. self.distance_min_tool = DistanceMin(self)
  1521. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1522. pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=True)
  1525. self.dblsidedtool = DblSidedTool(self)
  1526. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1527. self.cal_exc_tool = ToolCalibration(self)
  1528. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1529. before=self.dblsidedtool.menuAction,
  1530. separator=False)
  1531. self.align_objects_tool = AlignObjects(self)
  1532. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1533. self.edrills_tool = ToolExtractDrills(self)
  1534. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1535. self.panelize_tool = Panelize(self)
  1536. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1537. self.film_tool = Film(self)
  1538. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1539. self.paste_tool = SolderPaste(self)
  1540. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1541. self.calculator_tool = ToolCalculator(self)
  1542. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1543. self.sub_tool = ToolSub(self)
  1544. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1545. pos=self.ui.menutool, separator=True)
  1546. self.rules_tool = RulesCheck(self)
  1547. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1548. pos=self.ui.menutool, separator=False)
  1549. self.optimal_tool = ToolOptimal(self)
  1550. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1551. pos=self.ui.menutool, separator=True)
  1552. self.move_tool = ToolMove(self)
  1553. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin, separator=True)
  1555. self.cutout_tool = CutOut(self)
  1556. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1557. before=self.sub_tool.menuAction)
  1558. self.ncclear_tool = NonCopperClear(self)
  1559. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1560. before=self.sub_tool.menuAction, separator=True)
  1561. self.paint_tool = ToolPaint(self)
  1562. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1563. before=self.sub_tool.menuAction, separator=True)
  1564. self.isolation_tool = ToolIsolation(self)
  1565. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1566. before=self.sub_tool.menuAction, separator=True)
  1567. self.copper_thieving_tool = ToolCopperThieving(self)
  1568. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1569. pos=self.ui.menutool)
  1570. self.fiducial_tool = ToolFiducials(self)
  1571. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1572. pos=self.ui.menutool)
  1573. self.qrcode_tool = QRCode(self)
  1574. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1575. pos=self.ui.menutool)
  1576. self.punch_tool = ToolPunchGerber(self)
  1577. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1578. self.invert_tool = ToolInvertGerber(self)
  1579. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1580. self.corners_tool = ToolCorners(self)
  1581. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1582. self.etch_tool = ToolEtchCompensation(self)
  1583. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1584. self.transform_tool = ToolTransform(self)
  1585. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1586. pos=self.ui.menuoptions, separator=True)
  1587. self.properties_tool = Properties(self)
  1588. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1589. pos=self.ui.menuoptions)
  1590. self.pdf_tool = ToolPDF(self)
  1591. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1592. pos=self.ui.menufileimport,
  1593. separator=True)
  1594. self.image_tool = ToolImage(self)
  1595. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1596. pos=self.ui.menufileimport,
  1597. separator=True)
  1598. self.pcb_wizard_tool = PcbWizard(self)
  1599. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1600. pos=self.ui.menufileimport)
  1601. self.log.debug("Tools are installed.")
  1602. def remove_tools(self):
  1603. """
  1604. Will remove all the actions in the Tool menu.
  1605. :return: None
  1606. """
  1607. for act in self.ui.menutool.actions():
  1608. self.ui.menutool.removeAction(act)
  1609. def init_tools(self):
  1610. """
  1611. Initialize the Tool tab in the notebook side of the central widget.
  1612. Remove the actions in the Tools menu.
  1613. Instantiate again the FlatCAM tools (plugins).
  1614. All this is required when changing the layout: standard, compact etc.
  1615. :return: None
  1616. """
  1617. log.debug("init_tools()")
  1618. # delete the data currently in the Tools Tab and the Tab itself
  1619. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1620. if widget is not None:
  1621. widget.deleteLater()
  1622. self.ui.notebook.removeTab(2)
  1623. # rebuild the Tools Tab
  1624. self.ui.tool_tab = QtWidgets.QWidget()
  1625. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1626. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1627. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1628. self.ui.tool_scroll_area = VerticalScrollArea()
  1629. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1630. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1631. # first remove all of them
  1632. self.remove_tools()
  1633. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1634. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1635. '&Command Line\tS')
  1636. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1637. # third install all of them
  1638. try:
  1639. self.install_tools()
  1640. except AttributeError:
  1641. pass
  1642. self.log.debug("Tools are initialized.")
  1643. # def parse_system_fonts(self):
  1644. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1645. # 'params': []})
  1646. def connect_toolbar_signals(self):
  1647. """
  1648. Reconnect the signals to the actions in the toolbar.
  1649. This has to be done each time after the FlatCAM tools are removed/installed.
  1650. :return: None
  1651. """
  1652. # Toolbar
  1653. # File Toolbar Signals
  1654. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1655. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1656. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1657. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1658. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1659. # View Toolbar Signals
  1660. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1661. self.ui.replot_btn.triggered.connect(self.plot_all)
  1662. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1663. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1664. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1665. # Edit Toolbar Signals
  1666. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1667. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1668. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1669. self.ui.delete_btn.triggered.connect(self.on_delete)
  1670. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1671. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1672. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1673. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1674. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1675. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1676. # Scripting Toolbar Signals
  1677. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1678. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1679. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1680. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1681. # Tools Toolbar Signals
  1682. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1683. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1684. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1685. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1686. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1687. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1688. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1689. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1690. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1691. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1692. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1693. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1694. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1695. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1696. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1697. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1698. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1699. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1700. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1701. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1702. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1703. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1704. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1705. def object2editor(self):
  1706. """
  1707. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1708. :return: None
  1709. """
  1710. self.defaults.report_usage("object2editor()")
  1711. # disable the objects menu as it may interfere with the AppEditors
  1712. self.ui.menuobjects.setDisabled(True)
  1713. edited_object = self.collection.get_active()
  1714. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1715. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1716. pass
  1717. else:
  1718. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1719. return
  1720. if isinstance(edited_object, GeometryObject):
  1721. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1722. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1723. # we set the notebook to hidden
  1724. # self.ui.splitter.setSizes([0, 1])
  1725. if edited_object.multigeo is True:
  1726. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1727. if len(sel_rows) > 1:
  1728. self.inform.emit('[WARNING_NOTCL] %s' %
  1729. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1730. "is not possible.\n"
  1731. "Edit only one geometry at a time."))
  1732. # determine the tool dia of the selected tool
  1733. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1734. # now find the key in the edited_object.tools that has this tooldia
  1735. multi_tool = 1
  1736. for tool in edited_object.tools:
  1737. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1738. multi_tool = tool
  1739. break
  1740. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1741. else:
  1742. self.geo_editor.edit_fcgeometry(edited_object)
  1743. # set call source to the Editor we go into
  1744. self.call_source = 'geo_editor'
  1745. elif isinstance(edited_object, ExcellonObject):
  1746. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1747. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1748. if self.ui.splitter.sizes()[0] == 0:
  1749. self.ui.splitter.setSizes([1, 1])
  1750. self.exc_editor.edit_fcexcellon(edited_object)
  1751. # set call source to the Editor we go into
  1752. self.call_source = 'exc_editor'
  1753. elif isinstance(edited_object, GerberObject):
  1754. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1755. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1756. if self.ui.splitter.sizes()[0] == 0:
  1757. self.ui.splitter.setSizes([1, 1])
  1758. self.grb_editor.edit_fcgerber(edited_object)
  1759. # set call source to the Editor we go into
  1760. self.call_source = 'grb_editor'
  1761. # reset the following variables so the UI is built again after edit
  1762. edited_object.ui_build = False
  1763. edited_object.build_aperture_storage = False
  1764. elif isinstance(edited_object, CNCJobObject):
  1765. if self.ui.splitter.sizes()[0] == 0:
  1766. self.ui.splitter.setSizes([1, 1])
  1767. edited_object.on_edit_code_click()
  1768. return
  1769. # make sure that we can't select another object while in Editor Mode:
  1770. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1771. self.ui.project_frame.setDisabled(True)
  1772. # delete any selection shape that might be active as they are not relevant in Editor
  1773. self.delete_selection_shape()
  1774. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1775. self.ui.plot_tab_area.protectTab(0)
  1776. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1777. self.should_we_save = True
  1778. def editor2object(self, cleanup=None):
  1779. """
  1780. Transfers the Geometry or Excellon from it's editor to the current object.
  1781. :return: None
  1782. """
  1783. self.defaults.report_usage("editor2object()")
  1784. # re-enable the objects menu that was disabled on entry in Editor mode
  1785. self.ui.menuobjects.setDisabled(False)
  1786. # do not update a geometry or excellon object unless it comes out of an editor
  1787. if self.call_source != 'app':
  1788. edited_obj = self.collection.get_active()
  1789. if cleanup is None:
  1790. msgbox = QtWidgets.QMessageBox()
  1791. msgbox.setText(_("Do you want to save the edited object?"))
  1792. msgbox.setWindowTitle(_("Close Editor"))
  1793. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1794. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1795. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1796. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1797. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1798. msgbox.setDefaultButton(bt_yes)
  1799. msgbox.exec_()
  1800. response = msgbox.clickedButton()
  1801. if response == bt_yes:
  1802. # clean the Tools Tab
  1803. self.ui.tool_scroll_area.takeWidget()
  1804. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1805. self.ui.notebook.setTabText(2, "Tool")
  1806. if isinstance(edited_obj, GeometryObject):
  1807. obj_type = "Geometry"
  1808. self.geo_editor.update_fcgeometry(edited_obj)
  1809. # self.geo_editor.update_options(edited_obj)
  1810. # restore GUI to the Selected TAB
  1811. # Remove anything else in the AppGUI
  1812. self.ui.tool_scroll_area.takeWidget()
  1813. # update the geo object options so it is including the bounding box values
  1814. try:
  1815. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1816. edited_obj.options['xmin'] = xmin
  1817. edited_obj.options['ymin'] = ymin
  1818. edited_obj.options['xmax'] = xmax
  1819. edited_obj.options['ymax'] = ymax
  1820. except AttributeError as e:
  1821. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1822. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1823. edited_obj.build_ui()
  1824. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1825. elif isinstance(edited_obj, GerberObject):
  1826. obj_type = "Gerber"
  1827. self.grb_editor.update_fcgerber()
  1828. # self.grb_editor.update_options(edited_obj)
  1829. # delete the old object (the source object) if it was an empty one
  1830. try:
  1831. if len(edited_obj.solid_geometry) == 0:
  1832. old_name = edited_obj.options['name']
  1833. self.collection.delete_by_name(old_name)
  1834. except TypeError:
  1835. # if the solid_geometry is a single Polygon the len() will not work
  1836. # in any case, falling here means that we have something in the solid_geometry, even if only
  1837. # a single Polygon, therefore we pass this
  1838. pass
  1839. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1840. # restore GUI to the Selected TAB
  1841. # Remove anything else in the AppGUI
  1842. self.ui.selected_scroll_area.takeWidget()
  1843. elif isinstance(edited_obj, ExcellonObject):
  1844. obj_type = "Excellon"
  1845. self.exc_editor.update_fcexcellon(edited_obj)
  1846. # self.exc_editor.update_options(edited_obj)
  1847. # restore GUI to the Selected TAB
  1848. # Remove anything else in the AppGUI
  1849. self.ui.tool_scroll_area.takeWidget()
  1850. # delete the old object (the source object) if it was an empty one
  1851. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.delete_by_name(name=old_name)
  1854. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1855. else:
  1856. self.inform.emit('[WARNING_NOTCL] %s' %
  1857. _("Select a Gerber, Geometry or Excellon Object to update."))
  1858. return
  1859. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1860. elif response == bt_no:
  1861. # clean the Tools Tab
  1862. self.ui.tool_scroll_area.takeWidget()
  1863. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1864. self.ui.notebook.setTabText(2, "Tool")
  1865. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1866. if isinstance(edited_obj, GeometryObject):
  1867. self.geo_editor.deactivate()
  1868. edited_obj.build_ui()
  1869. elif isinstance(edited_obj, GerberObject):
  1870. self.grb_editor.deactivate_grb_editor()
  1871. edited_obj.build_ui()
  1872. elif isinstance(edited_obj, ExcellonObject):
  1873. self.exc_editor.deactivate()
  1874. edited_obj.build_ui()
  1875. else:
  1876. self.inform.emit('[WARNING_NOTCL] %s' %
  1877. _("Select a Gerber, Geometry or Excellon Object to update."))
  1878. return
  1879. elif response == bt_cancel:
  1880. return
  1881. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1882. # edited_obj.build_ui()
  1883. # Switch notebook to Selected page
  1884. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1885. else:
  1886. if isinstance(edited_obj, GeometryObject):
  1887. self.geo_editor.deactivate()
  1888. elif isinstance(edited_obj, GerberObject):
  1889. self.grb_editor.deactivate_grb_editor()
  1890. elif isinstance(edited_obj, ExcellonObject):
  1891. self.exc_editor.deactivate()
  1892. else:
  1893. self.inform.emit('[WARNING_NOTCL] %s' %
  1894. _("Select a Gerber, Geometry or Excellon Object to update."))
  1895. return
  1896. # if notebook is hidden we show it
  1897. if self.ui.splitter.sizes()[0] == 0:
  1898. self.ui.splitter.setSizes([1, 1])
  1899. # restore the call_source to app
  1900. self.call_source = 'app'
  1901. # edited_obj.plot()
  1902. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1903. self.ui.plot_tab_area.protectTab(0)
  1904. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1905. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1906. self.ui.project_frame.setDisabled(False)
  1907. def get_last_folder(self):
  1908. """
  1909. Get the folder path from where the last file was opened.
  1910. :return: String, last opened folder path
  1911. """
  1912. return self.defaults["global_last_folder"]
  1913. def get_last_save_folder(self):
  1914. """
  1915. Get the folder path from where the last file was saved.
  1916. :return: String, last saved folder path
  1917. """
  1918. loc = self.defaults["global_last_save_folder"]
  1919. if loc is None:
  1920. loc = self.defaults["global_last_folder"]
  1921. if loc is None:
  1922. loc = os.path.dirname(__file__)
  1923. return loc
  1924. def info(self, msg):
  1925. """
  1926. Informs the user. Normally on the status bar, optionally
  1927. also on the shell.
  1928. :param msg: Text to write.
  1929. :return: None
  1930. """
  1931. # Type of message in brackets at the beginning of the message.
  1932. match = re.search(r"\[(.*)\](.*)", msg)
  1933. if match:
  1934. level = match.group(1)
  1935. msg_ = match.group(2)
  1936. self.ui.fcinfo.set_status(str(msg_), level=level)
  1937. if level.lower() == "error":
  1938. self.shell_message(msg, error=True, show=True)
  1939. elif level.lower() == "warning":
  1940. self.shell_message(msg, warning=True, show=True)
  1941. elif level.lower() == "error_notcl":
  1942. self.shell_message(msg, error=True, show=False)
  1943. elif level.lower() == "warning_notcl":
  1944. self.shell_message(msg, warning=True, show=False)
  1945. elif level.lower() == "success":
  1946. self.shell_message(msg, success=True, show=False)
  1947. elif level.lower() == "selected":
  1948. self.shell_message(msg, selected=True, show=False)
  1949. else:
  1950. self.shell_message(msg, show=False)
  1951. else:
  1952. self.ui.fcinfo.set_status(str(msg), level="info")
  1953. # make sure that if the message is to clear the infobar with a space
  1954. # is not printed over and over on the shell
  1955. if msg != '':
  1956. self.shell_message(msg)
  1957. def on_import_preferences(self):
  1958. """
  1959. Loads the application default settings from a saved file into
  1960. ``self.defaults`` dictionary.
  1961. :return: None
  1962. """
  1963. self.defaults.report_usage("on_import_preferences")
  1964. App.log.debug("App.on_import_preferences()")
  1965. # Show file chooser
  1966. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1967. try:
  1968. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1969. directory=self.data_path,
  1970. filter=filter_)
  1971. except TypeError:
  1972. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1973. filter=filter_)
  1974. filename = str(filename)
  1975. if filename == "":
  1976. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1977. return
  1978. # Load in the defaults from the chosen file
  1979. self.defaults.load(filename=filename)
  1980. self.preferencesUiManager.on_preferences_edited()
  1981. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1982. def on_export_preferences(self):
  1983. """
  1984. Save the defaults dictionary to a file.
  1985. :return: None
  1986. """
  1987. self.defaults.report_usage("on_export_preferences")
  1988. App.log.debug("on_export_preferences()")
  1989. # defaults_file_content = None
  1990. # Show file chooser
  1991. date = str(datetime.today()).rpartition('.')[0]
  1992. date = ''.join(c for c in date if c not in ':-')
  1993. date = date.replace(' ', '_')
  1994. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1995. try:
  1996. filename, _f = FCFileSaveDialog.get_saved_filename(
  1997. caption=_("Export FlatCAM Preferences"),
  1998. directory=self.data_path + '/preferences_' + date,
  1999. filter=filter__
  2000. )
  2001. except TypeError:
  2002. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2003. filename = str(filename)
  2004. if filename == "":
  2005. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2006. return
  2007. # Update options
  2008. self.preferencesUiManager.defaults_read_form()
  2009. self.defaults.propagate_defaults()
  2010. # Save update options
  2011. try:
  2012. self.defaults.write(filename=filename)
  2013. except Exception:
  2014. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2015. return
  2016. if self.defaults["global_open_style"] is False:
  2017. self.file_opened.emit("preferences", filename)
  2018. self.file_saved.emit("preferences", filename)
  2019. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2020. def save_to_file(self, content_to_save, txt_content):
  2021. """
  2022. Save something to a file.
  2023. :return: None
  2024. """
  2025. self.defaults.report_usage("save_to_file")
  2026. App.log.debug("save_to_file()")
  2027. self.date = str(datetime.today()).rpartition('.')[0]
  2028. self.date = ''.join(c for c in self.date if c not in ':-')
  2029. self.date = self.date.replace(' ', '_')
  2030. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2031. path_to_save = self.defaults["global_last_save_folder"] if \
  2032. self.defaults["global_last_save_folder"] is not None else self.data_path
  2033. try:
  2034. filename, _f = FCFileSaveDialog.get_saved_filename(
  2035. caption=_("Save to file"),
  2036. directory=path_to_save + '/file_' + self.date,
  2037. filter=filter__
  2038. )
  2039. except TypeError:
  2040. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2041. filename = str(filename)
  2042. if filename == "":
  2043. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2044. return
  2045. else:
  2046. try:
  2047. with open(filename, 'w') as f:
  2048. ___ = f.read()
  2049. except PermissionError:
  2050. self.inform.emit('[WARNING] %s' %
  2051. _("Permission denied, saving not possible.\n"
  2052. "Most likely another app is holding the file open and not accessible."))
  2053. return
  2054. except IOError:
  2055. App.log.debug('Creating a new file ...')
  2056. f = open(filename, 'w')
  2057. f.close()
  2058. except Exception:
  2059. e = sys.exc_info()[0]
  2060. App.log.error("Could not load the file.")
  2061. App.log.error(str(e))
  2062. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2063. return
  2064. # Save content
  2065. if filename.rpartition('.')[2].lower() == 'html':
  2066. file_content = content_to_save
  2067. else:
  2068. file_content = txt_content
  2069. try:
  2070. with open(filename, "w") as f:
  2071. f.write(file_content)
  2072. except Exception:
  2073. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2074. return
  2075. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2076. def register_recent(self, kind, filename):
  2077. """
  2078. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2079. dictionary.
  2080. :param kind: type of file that was opened
  2081. :param filename: the path and file name for the file that was opened
  2082. :return:
  2083. """
  2084. self.log.debug("register_recent()")
  2085. self.log.debug(" %s" % kind)
  2086. self.log.debug(" %s" % filename)
  2087. record = {'kind': str(kind), 'filename': str(filename)}
  2088. if record in self.recent:
  2089. return
  2090. if record in self.recent_projects:
  2091. return
  2092. if record['kind'] == 'project':
  2093. self.recent_projects.insert(0, record)
  2094. else:
  2095. self.recent.insert(0, record)
  2096. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2097. self.recent.pop()
  2098. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2099. self.recent_projects.pop()
  2100. try:
  2101. f = open(self.data_path + '/recent.json', 'w')
  2102. except IOError:
  2103. App.log.error("Failed to open recent items file for writing.")
  2104. self.inform.emit('[ERROR_NOTCL] %s' %
  2105. _('Failed to open recent files file for writing.'))
  2106. return
  2107. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2108. f.close()
  2109. try:
  2110. fp = open(self.data_path + '/recent_projects.json', 'w')
  2111. except IOError:
  2112. App.log.error("Failed to open recent items file for writing.")
  2113. self.inform.emit('[ERROR_NOTCL] %s' %
  2114. _('Failed to open recent projects file for writing.'))
  2115. return
  2116. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2117. fp.close()
  2118. # Re-build the recent items menu
  2119. self.setup_recent_items()
  2120. def on_about(self):
  2121. """
  2122. Displays the "about" dialog found in the Menu --> Help.
  2123. :return: None
  2124. """
  2125. self.defaults.report_usage("on_about")
  2126. version = self.version
  2127. version_date = self.version_date
  2128. beta = self.beta
  2129. class AboutDialog(QtWidgets.QDialog):
  2130. def __init__(self, app, parent=None):
  2131. QtWidgets.QDialog.__init__(self, parent)
  2132. self.app = app
  2133. # Icon and title
  2134. self.setWindowIcon(parent.app_icon)
  2135. self.setWindowTitle(_("About FlatCAM"))
  2136. self.resize(600, 200)
  2137. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2138. # self.setStyleSheet(
  2139. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2140. # "background-attachment: fixed"
  2141. # )
  2142. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2143. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2144. # palette = QtGui.QPalette()
  2145. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2146. # self.setPalette(palette)
  2147. logo = QtWidgets.QLabel()
  2148. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2149. title = QtWidgets.QLabel(
  2150. "<font size=8><B>FlatCAM</B></font><BR>"
  2151. "{title}<BR>"
  2152. "<BR>"
  2153. "<BR>"
  2154. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2155. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2156. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2157. "<B>{issue}</B></a><BR>".format(
  2158. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2159. devel=_("Development"),
  2160. down=_("DOWNLOAD"),
  2161. issue=_("Issue tracker"))
  2162. )
  2163. title.setOpenExternalLinks(True)
  2164. closebtn = QtWidgets.QPushButton(_("Close"))
  2165. tab_widget = QtWidgets.QTabWidget()
  2166. description_label = QtWidgets.QLabel(
  2167. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2168. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2169. version=version,
  2170. beta=('BETA' if beta else ''),
  2171. date=version_date,
  2172. arch=platform.architecture()[0])
  2173. )
  2174. description_label.setOpenExternalLinks(True)
  2175. lic_lbl_header = QtWidgets.QLabel(
  2176. '%s:<br>%s<br>' % (
  2177. _('Licensed under the MIT license'),
  2178. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2179. "http://www.opensource.org/licenses/mit-license.php</a>"
  2180. )
  2181. )
  2182. lic_lbl_header.setOpenExternalLinks(True)
  2183. lic_lbl_body = QtWidgets.QLabel(
  2184. _(
  2185. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2186. 'of this software and associated documentation files (the "Software"), to deal\n'
  2187. 'in the Software without restriction, including without limitation the rights\n'
  2188. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2189. 'copies of the Software, and to permit persons to whom the Software is\n'
  2190. 'furnished to do so, subject to the following conditions:\n\n'
  2191. 'The above copyright notice and this permission notice shall be included in\n'
  2192. 'all copies or substantial portions of the Software.\n\n'
  2193. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2194. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2195. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2196. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2197. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2198. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2199. 'THE SOFTWARE.'
  2200. )
  2201. )
  2202. attributions_label = QtWidgets.QLabel(
  2203. _(
  2204. 'Some of the icons used are from the following sources:<br>'
  2205. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2206. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2207. 'title="Flaticon">www.flaticon.com</a></div>'
  2208. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2209. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2210. )
  2211. )
  2212. attributions_label.setOpenExternalLinks(True)
  2213. # layouts
  2214. layout1 = QtWidgets.QVBoxLayout()
  2215. layout1_1 = QtWidgets.QHBoxLayout()
  2216. layout1_2 = QtWidgets.QHBoxLayout()
  2217. layout2 = QtWidgets.QHBoxLayout()
  2218. layout3 = QtWidgets.QHBoxLayout()
  2219. self.setLayout(layout1)
  2220. layout1.addLayout(layout1_1)
  2221. layout1.addLayout(layout1_2)
  2222. layout1.addLayout(layout2)
  2223. layout1.addLayout(layout3)
  2224. layout1_1.addStretch()
  2225. layout1_1.addWidget(description_label)
  2226. layout1_2.addWidget(tab_widget)
  2227. self.splash_tab = QtWidgets.QWidget()
  2228. self.splash_tab.setObjectName("splash_about")
  2229. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2230. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2231. tab_widget.addTab(self.splash_tab, _("Splash"))
  2232. self.programmmers_tab = QtWidgets.QWidget()
  2233. self.programmmers_tab.setObjectName("programmers_about")
  2234. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2235. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2236. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2237. self.translators_tab = QtWidgets.QWidget()
  2238. self.translators_tab.setObjectName("translators_about")
  2239. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2240. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2241. tab_widget.addTab(self.translators_tab, _("Translators"))
  2242. self.license_tab = QtWidgets.QWidget()
  2243. self.license_tab.setObjectName("license_about")
  2244. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2245. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2246. tab_widget.addTab(self.license_tab, _("License"))
  2247. self.attributions_tab = QtWidgets.QWidget()
  2248. self.attributions_tab.setObjectName("attributions_about")
  2249. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2250. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2251. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2252. self.splash_tab_layout.addWidget(logo, stretch=0)
  2253. self.splash_tab_layout.addWidget(title, stretch=1)
  2254. pal = QtGui.QPalette()
  2255. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2256. self.prog_grid_lay = QtWidgets.QGridLayout()
  2257. self.prog_grid_lay.setHorizontalSpacing(20)
  2258. self.prog_grid_lay.setColumnStretch(0, 0)
  2259. self.prog_grid_lay.setColumnStretch(2, 1)
  2260. prog_widget = QtWidgets.QWidget()
  2261. prog_widget.setLayout(self.prog_grid_lay)
  2262. prog_scroll = QtWidgets.QScrollArea()
  2263. prog_scroll.setWidget(prog_widget)
  2264. prog_scroll.setWidgetResizable(True)
  2265. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2266. prog_scroll.setPalette(pal)
  2267. self.programmmers_tab_layout.addWidget(prog_scroll)
  2268. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2269. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2270. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2271. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2315. self.translator_grid_lay = QtWidgets.QGridLayout()
  2316. self.translator_grid_lay.setColumnStretch(0, 0)
  2317. self.translator_grid_lay.setColumnStretch(1, 0)
  2318. self.translator_grid_lay.setColumnStretch(2, 1)
  2319. self.translator_grid_lay.setColumnStretch(3, 0)
  2320. # trans_widget = QtWidgets.QWidget()
  2321. # trans_widget.setLayout(self.translator_grid_lay)
  2322. # self.translators_tab_layout.addWidget(trans_widget)
  2323. # self.translators_tab_layout.addStretch()
  2324. trans_widget = QtWidgets.QWidget()
  2325. trans_widget.setLayout(self.translator_grid_lay)
  2326. trans_scroll = QtWidgets.QScrollArea()
  2327. trans_scroll.setWidget(trans_widget)
  2328. trans_scroll.setWidgetResizable(True)
  2329. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2330. trans_scroll.setPalette(pal)
  2331. self.translators_tab_layout.addWidget(trans_scroll)
  2332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2365. self.translator_grid_lay.setColumnStretch(0, 0)
  2366. self.translators_tab_layout.addStretch()
  2367. self.license_tab_layout.addWidget(lic_lbl_header)
  2368. self.license_tab_layout.addWidget(lic_lbl_body)
  2369. self.license_tab_layout.addStretch()
  2370. self.attributions_tab_layout.addWidget(attributions_label)
  2371. self.attributions_tab_layout.addStretch()
  2372. layout3.addStretch()
  2373. layout3.addWidget(closebtn)
  2374. closebtn.clicked.connect(self.accept)
  2375. AboutDialog(app=self, parent=self.ui).exec_()
  2376. def on_readme(self):
  2377. class AboutDialog(QtWidgets.QDialog):
  2378. def __init__(self, app, parent=None):
  2379. QtWidgets.QDialog.__init__(self, parent)
  2380. self.app = app
  2381. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2382. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2383. "<b>new features</b></a>"
  2384. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2385. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2386. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2387. # Icon and title
  2388. self.setWindowIcon(parent.app_icon)
  2389. self.setWindowTitle(_("Important Information's"))
  2390. self.resize(720, 330)
  2391. logo = QtWidgets.QLabel()
  2392. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2393. content = QtWidgets.QLabel(
  2394. "This program is %s and free in a very wide meaning of the word.<br>"
  2395. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2396. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2397. "you can <b>contribute</b> to the development yourself by:<br>"
  2398. "<ul>"
  2399. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2400. "<li>%s by providing the steps required to reproduce the bug</li>"
  2401. "<li>or by making a %s.</li>"
  2402. "</ul>"
  2403. "There are no strings attached.<br>"
  2404. "You don't have to make a %s, and it is totally optional but:"
  2405. "<ul>"
  2406. "<li>it will be welcomed with joy &#128077;</li>"
  2407. "<li>it will give me a reason to continue &#128513;</li>"
  2408. "</ul>" %
  2409. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2410. )
  2411. content.setOpenExternalLinks(True)
  2412. closebtn = QtWidgets.QPushButton(_("Close"))
  2413. # layouts
  2414. layout1 = QtWidgets.QVBoxLayout()
  2415. self.setLayout(layout1)
  2416. pal = QtGui.QPalette()
  2417. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2418. self.grid_lay = QtWidgets.QGridLayout()
  2419. self.grid_lay.setHorizontalSpacing(20)
  2420. self.grid_lay.setColumnStretch(0, 0)
  2421. self.grid_lay.setColumnStretch(1, 1)
  2422. content_widget = QtWidgets.QWidget()
  2423. content_widget.setLayout(self.grid_lay)
  2424. scroll_area = QtWidgets.QScrollArea()
  2425. scroll_area.setWidget(content_widget)
  2426. scroll_area.setWidgetResizable(True)
  2427. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2428. scroll_area.setPalette(pal)
  2429. self.grid_lay.addWidget(logo, 0, 0)
  2430. self.grid_lay.addWidget(content, 0, 1)
  2431. layout1.addWidget(scroll_area)
  2432. layout2 = QtWidgets.QHBoxLayout()
  2433. layout1.addLayout(layout2)
  2434. layout2.addStretch()
  2435. layout2.addWidget(closebtn)
  2436. closebtn.clicked.connect(self.accept)
  2437. AboutDialog(app=self, parent=self.ui).exec_()
  2438. def install_bookmarks(self, book_dict=None):
  2439. """
  2440. Install the bookmarks actions in the Help menu -> Bookmarks
  2441. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2442. :return: None
  2443. """
  2444. if book_dict is None:
  2445. self.defaults["global_bookmarks"].update(
  2446. {
  2447. '1': ['FlatCAM', "http://flatcam.org"],
  2448. '2': ['Backup Site', ""]
  2449. }
  2450. )
  2451. else:
  2452. self.defaults["global_bookmarks"].clear()
  2453. self.defaults["global_bookmarks"].update(book_dict)
  2454. # first try to disconnect if somehow they get connected from elsewhere
  2455. for act in self.ui.menuhelp_bookmarks.actions():
  2456. try:
  2457. act.triggered.disconnect()
  2458. except TypeError:
  2459. pass
  2460. # clear all actions except the last one who is the Bookmark manager
  2461. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2462. pass
  2463. else:
  2464. self.ui.menuhelp_bookmarks.removeAction(act)
  2465. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2466. if self.defaults["global_bookmarks"]:
  2467. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2468. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2469. # the JSON is first making the keys as strings (therefore I have to use strings too
  2470. # or do the conversion :(
  2471. # )
  2472. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2473. # the '10' entry jsut after '1' therefore ordering as strings
  2474. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2475. key=lambda x: int(x[0]))
  2476. for entry, bookmark in sorted_bookmarks:
  2477. title = bookmark[0]
  2478. weblink = bookmark[1]
  2479. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2480. act.setText(title)
  2481. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2482. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2483. if title == 'Backup Site' and weblink == "":
  2484. act.triggered.connect(self.on_backup_site)
  2485. else:
  2486. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2487. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2488. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2489. def on_bookmarks_manager(self):
  2490. """
  2491. Adds the bookmark manager in a Tab in Plot Area
  2492. :return:
  2493. """
  2494. for idx in range(self.ui.plot_tab_area.count()):
  2495. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2496. # there can be only one instance of Bookmark Manager at one time
  2497. return
  2498. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2499. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2500. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2501. # add the tab if it was closed
  2502. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2503. # delete the absolute and relative position and messages in the infobar
  2504. self.ui.position_label.setText("")
  2505. # self.ui.rel_position_label.setText("")
  2506. # Switch plot_area to preferences page
  2507. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2508. def on_backup_site(self):
  2509. msgbox = QtWidgets.QMessageBox()
  2510. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2511. "1. FlatCAM.org website is down\n"
  2512. "2. Someone forked FlatCAM project and wants to point\n"
  2513. "to his own website\n\n"
  2514. "If you can't get any informations about FlatCAM beta\n"
  2515. "use the YouTube channel link from the Help menu."))
  2516. msgbox.setWindowTitle(_("Alternative website"))
  2517. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2518. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2519. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2520. msgbox.setDefaultButton(bt_yes)
  2521. msgbox.exec_()
  2522. # response = msgbox.clickedButton()
  2523. def on_file_savedefaults(self):
  2524. """
  2525. Callback for menu item File->Save Defaults. Saves application default options
  2526. ``self.defaults`` to current_defaults.FlatConfig.
  2527. :return: None
  2528. """
  2529. self.preferencesUiManager.save_defaults()
  2530. def final_save(self):
  2531. """
  2532. Callback for doing a preferences save to file whenever the application is about to quit.
  2533. If the project has changes, it will ask the user to save the project.
  2534. :return: None
  2535. """
  2536. if self.save_in_progress:
  2537. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2538. return
  2539. if self.should_we_save and self.collection.get_list():
  2540. msgbox = QtWidgets.QMessageBox()
  2541. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2542. "\n"
  2543. "Do you want to Save the project?"))
  2544. msgbox.setWindowTitle(_("Save changes"))
  2545. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2546. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2547. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2548. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2549. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2550. msgbox.setDefaultButton(bt_yes)
  2551. msgbox.exec_()
  2552. response = msgbox.clickedButton()
  2553. if response == bt_yes:
  2554. try:
  2555. self.trayIcon.hide()
  2556. except Exception:
  2557. pass
  2558. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2559. elif response == bt_no:
  2560. try:
  2561. self.trayIcon.hide()
  2562. except Exception:
  2563. pass
  2564. self.quit_application()
  2565. elif response == bt_cancel:
  2566. return
  2567. else:
  2568. try:
  2569. self.trayIcon.hide()
  2570. except Exception:
  2571. pass
  2572. self.quit_application()
  2573. def quit_application(self):
  2574. """
  2575. Called (as a pyslot or not) when the application is quit.
  2576. :return: None
  2577. """
  2578. self.preferencesUiManager.save_defaults(silent=True)
  2579. log.debug("App.quit_application() --> App Defaults saved.")
  2580. if self.cmd_line_headless != 1:
  2581. # save app state to file
  2582. stgs = QSettings("Open Source", "FlatCAM")
  2583. stgs.setValue('saved_gui_state', self.ui.saveState())
  2584. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2585. stgs.setValue(
  2586. 'language',
  2587. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2588. )
  2589. stgs.setValue(
  2590. 'notebook_font_size',
  2591. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2592. )
  2593. stgs.setValue(
  2594. 'axis_font_size',
  2595. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2596. )
  2597. stgs.setValue(
  2598. 'textbox_font_size',
  2599. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2600. )
  2601. stgs.setValue(
  2602. 'hud_font_size',
  2603. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2604. )
  2605. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2606. stgs.setValue(
  2607. 'machinist',
  2608. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2609. )
  2610. # This will write the setting to the platform specific storage.
  2611. del stgs
  2612. log.debug("App.quit_application() --> App UI state saved.")
  2613. # try to quit the Socket opened by ArgsThread class
  2614. try:
  2615. self.new_launch.stop.emit()
  2616. except Exception as err:
  2617. log.debug("App.quit_application() --> %s" % str(err))
  2618. # try to quit the QThread that run ArgsThread class
  2619. try:
  2620. self.th.quit()
  2621. except Exception as e:
  2622. log.debug("App.quit_application() --> %s" % str(e))
  2623. # terminate workers
  2624. self.workers.__del__()
  2625. # quit app by signalling for self.kill_app() method
  2626. # self.close_app_signal.emit()
  2627. QtWidgets.qApp.quit()
  2628. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2629. # we use the following command
  2630. minor_v = sys.version_info.minor
  2631. if minor_v < 8:
  2632. sys.exit(0)
  2633. else:
  2634. os._exit(0) # fix to work with Python 3.8
  2635. @staticmethod
  2636. def kill_app():
  2637. QtWidgets.qApp.quit()
  2638. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2639. # we use the following command
  2640. sys.exit(0)
  2641. def on_portable_checked(self, state):
  2642. """
  2643. Callback called when the checkbox in Preferences GUI is checked.
  2644. It will set the application as portable by creating the preferences and recent files in the
  2645. 'config' folder found in the FlatCAM installation folder.
  2646. :param state: boolean, the state of the checkbox when clicked/checked
  2647. :return:
  2648. """
  2649. line_no = 0
  2650. data = None
  2651. if sys.platform != 'win32':
  2652. # this won't work in Linux or MacOS
  2653. return
  2654. # test if the app was frozen and choose the path for the configuration file
  2655. if getattr(sys, "frozen", False) is True:
  2656. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2657. else:
  2658. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2659. config_file = current_data_path + '\\configuration.txt'
  2660. try:
  2661. with open(config_file, 'r') as f:
  2662. try:
  2663. data = f.readlines()
  2664. except Exception as e:
  2665. log.debug('App.__init__() -->%s' % str(e))
  2666. return
  2667. except FileNotFoundError:
  2668. pass
  2669. for line in data:
  2670. line = line.strip('\n')
  2671. param = str(line).rpartition('=')
  2672. if param[0] == 'portable':
  2673. break
  2674. line_no += 1
  2675. if state:
  2676. data[line_no] = 'portable=True\n'
  2677. # create the new defauults files
  2678. # create current_defaults.FlatConfig file if there is none
  2679. try:
  2680. f = open(current_data_path + '/current_defaults.FlatConfig')
  2681. f.close()
  2682. except IOError:
  2683. App.log.debug('Creating empty current_defaults.FlatConfig')
  2684. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2685. json.dump({}, f)
  2686. f.close()
  2687. # create factory_defaults.FlatConfig file if there is none
  2688. try:
  2689. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2690. f.close()
  2691. except IOError:
  2692. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2693. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2694. json.dump({}, f)
  2695. f.close()
  2696. try:
  2697. f = open(current_data_path + '/recent.json')
  2698. f.close()
  2699. except IOError:
  2700. App.log.debug('Creating empty recent.json')
  2701. f = open(current_data_path + '/recent.json', 'w')
  2702. json.dump([], f)
  2703. f.close()
  2704. try:
  2705. fp = open(current_data_path + '/recent_projects.json')
  2706. fp.close()
  2707. except IOError:
  2708. App.log.debug('Creating empty recent_projects.json')
  2709. fp = open(current_data_path + '/recent_projects.json', 'w')
  2710. json.dump([], fp)
  2711. fp.close()
  2712. # save the current defaults to the new defaults file
  2713. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2714. else:
  2715. data[line_no] = 'portable=False\n'
  2716. with open(config_file, 'w') as f:
  2717. f.writelines(data)
  2718. def on_register_files(self, obj_type=None):
  2719. """
  2720. Called whenever there is a need to register file extensions with FlatCAM.
  2721. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2722. :param obj_type: the type of object to be register for.
  2723. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2724. :return: None
  2725. """
  2726. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2727. new_reg_path = 'Software\\Classes\\'
  2728. # find if the current user is admin
  2729. try:
  2730. is_admin = os.getuid() == 0
  2731. except AttributeError:
  2732. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2733. if is_admin is True:
  2734. root_path = winreg.HKEY_LOCAL_MACHINE
  2735. else:
  2736. root_path = winreg.HKEY_CURRENT_USER
  2737. # create the keys
  2738. def set_reg(name, root_pth, new_reg_path, value):
  2739. try:
  2740. winreg.CreateKey(root_pth, new_reg_path)
  2741. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2742. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2743. return True
  2744. except WindowsError:
  2745. return False
  2746. # delete key in registry
  2747. def delete_reg(root_pth, reg_path, key_to_del):
  2748. key_to_del_path = reg_path + key_to_del
  2749. try:
  2750. winreg.DeleteKey(root_pth, key_to_del_path)
  2751. return True
  2752. except WindowsError:
  2753. return False
  2754. if obj_type is None or obj_type == 'excellon':
  2755. exc_list = \
  2756. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2757. exc_list = [x for x in exc_list if x != '']
  2758. # register all keys in the Preferences window
  2759. for ext in exc_list:
  2760. new_k = new_reg_path + '.%s' % ext
  2761. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2762. # and unregister those that are no longer in the Preferences windows but are in the file
  2763. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2764. if ext not in exc_list:
  2765. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2766. # now write the updated extensions to the self.defaults
  2767. # new_ext = ''
  2768. # for ext in exc_list:
  2769. # new_ext = new_ext + ext + ', '
  2770. # self.defaults["fa_excellon"] = new_ext
  2771. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2772. if obj_type is None or obj_type == 'gcode':
  2773. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2774. gco_list = [x for x in gco_list if x != '']
  2775. # register all keys in the Preferences window
  2776. for ext in gco_list:
  2777. new_k = new_reg_path + '.%s' % ext
  2778. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2779. # and unregister those that are no longer in the Preferences windows but are in the file
  2780. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2781. if ext not in gco_list:
  2782. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2783. # now write the updated extensions to the self.defaults
  2784. # new_ext = ''
  2785. # for ext in gco_list:
  2786. # new_ext = new_ext + ext + ', '
  2787. # self.defaults["fa_gcode"] = new_ext
  2788. self.inform.emit('[success] %s' %
  2789. _("Selected GCode file extensions registered with FlatCAM."))
  2790. if obj_type is None or obj_type == 'gerber':
  2791. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2792. grb_list = [x for x in grb_list if x != '']
  2793. # register all keys in the Preferences window
  2794. for ext in grb_list:
  2795. new_k = new_reg_path + '.%s' % ext
  2796. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2797. # and unregister those that are no longer in the Preferences windows but are in the file
  2798. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2799. if ext not in grb_list:
  2800. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2801. # now write the updated extensions to the self.defaults
  2802. # new_ext = ''
  2803. # for ext in grb_list:
  2804. # new_ext = new_ext + ext + ', '
  2805. # self.defaults["fa_gerber"] = new_ext
  2806. self.inform.emit('[success] %s' %
  2807. _("Selected Gerber file extensions registered with FlatCAM."))
  2808. def add_extension(self, ext_type):
  2809. """
  2810. Add a file extension to the list for a specific object
  2811. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2812. :return:
  2813. """
  2814. if ext_type == 'excellon':
  2815. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2816. if new_ext == '':
  2817. return
  2818. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2819. if new_ext in old_val:
  2820. return
  2821. old_val.append(new_ext)
  2822. old_val.sort()
  2823. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2824. if ext_type == 'gcode':
  2825. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2826. if new_ext == '':
  2827. return
  2828. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2829. if new_ext in old_val:
  2830. return
  2831. old_val.append(new_ext)
  2832. old_val.sort()
  2833. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2834. if ext_type == 'gerber':
  2835. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2836. if new_ext == '':
  2837. return
  2838. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2839. if new_ext in old_val:
  2840. return
  2841. old_val.append(new_ext)
  2842. old_val.sort()
  2843. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2844. if ext_type == 'keyword':
  2845. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2846. if new_kw == '':
  2847. return
  2848. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2849. if new_kw in old_val:
  2850. return
  2851. old_val.append(new_kw)
  2852. old_val.sort()
  2853. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2854. # update the self.myKeywords so the model is updated
  2855. self.autocomplete_kw_list = \
  2856. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2857. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2858. self.shell._edit.set_model_data(self.myKeywords)
  2859. def del_extension(self, ext_type):
  2860. """
  2861. Remove a file extension from the list for a specific object
  2862. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2863. :return:
  2864. """
  2865. if ext_type == 'excellon':
  2866. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2867. if new_ext == '':
  2868. return
  2869. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2870. if new_ext not in old_val:
  2871. return
  2872. old_val.remove(new_ext)
  2873. old_val.sort()
  2874. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2875. if ext_type == 'gcode':
  2876. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2877. if new_ext == '':
  2878. return
  2879. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2880. if new_ext not in old_val:
  2881. return
  2882. old_val.remove(new_ext)
  2883. old_val.sort()
  2884. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2885. if ext_type == 'gerber':
  2886. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2887. if new_ext == '':
  2888. return
  2889. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2890. if new_ext not in old_val:
  2891. return
  2892. old_val.remove(new_ext)
  2893. old_val.sort()
  2894. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2895. if ext_type == 'keyword':
  2896. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2897. if new_kw == '':
  2898. return
  2899. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2900. if new_kw not in old_val:
  2901. return
  2902. old_val.remove(new_kw)
  2903. old_val.sort()
  2904. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2905. # update the self.myKeywords so the model is updated
  2906. self.autocomplete_kw_list = \
  2907. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2908. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2909. self.shell._edit.set_model_data(self.myKeywords)
  2910. def restore_extensions(self, ext_type):
  2911. """
  2912. Restore all file extensions associations with FlatCAM, for a specific object
  2913. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2914. :return:
  2915. """
  2916. if ext_type == 'excellon':
  2917. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2918. # for the ability to open Excellon files with .txt extension
  2919. new_exc_list = deepcopy(self.exc_list)
  2920. try:
  2921. new_exc_list.remove('txt')
  2922. except ValueError:
  2923. pass
  2924. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2925. if ext_type == 'gcode':
  2926. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2927. if ext_type == 'gerber':
  2928. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2929. if ext_type == 'keyword':
  2930. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2931. # update the self.myKeywords so the model is updated
  2932. self.autocomplete_kw_list = self.default_keywords
  2933. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2934. self.shell._edit.set_model_data(self.myKeywords)
  2935. def delete_all_extensions(self, ext_type):
  2936. """
  2937. Delete all file extensions associations with FlatCAM, for a specific object
  2938. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2939. :return:
  2940. """
  2941. if ext_type == 'excellon':
  2942. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2943. if ext_type == 'gcode':
  2944. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2945. if ext_type == 'gerber':
  2946. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2947. if ext_type == 'keyword':
  2948. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2949. # update the self.myKeywords so the model is updated
  2950. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2951. self.shell._edit.set_model_data(self.myKeywords)
  2952. def on_edit_join(self, name=None):
  2953. """
  2954. Callback for Edit->Join. Joins the selected geometry objects into
  2955. a new one.
  2956. :return: None
  2957. """
  2958. self.defaults.report_usage("on_edit_join()")
  2959. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2960. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2961. geo_type_set = set()
  2962. objs = self.collection.get_selected()
  2963. if len(objs) < 2:
  2964. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2965. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2966. return 'fail'
  2967. for obj in objs:
  2968. geo_type_set.add(obj.multigeo)
  2969. # if len(geo_type_list) == 1 means that all list elements are the same
  2970. if len(geo_type_set) != 1:
  2971. self.inform.emit('[ERROR] %s' %
  2972. _("Failed join. The Geometry objects are of different types.\n"
  2973. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2974. "convert from one to another and retry joining \n"
  2975. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2976. "the result may not be what was expected. \n"
  2977. "Check the generated GCODE."))
  2978. return
  2979. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2980. if True in geo_type_set:
  2981. def initialize(geo_obj, app):
  2982. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2983. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2984. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2985. for v in geo_obj.tools.values():
  2986. v['data']['name'] = obj_name_multi
  2987. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2988. else:
  2989. def initialize(geo_obj, app):
  2990. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2991. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2992. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2993. for v in geo_obj.tools.values():
  2994. v['data']['name'] = obj_name_single
  2995. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2996. self.should_we_save = True
  2997. def on_edit_join_exc(self):
  2998. """
  2999. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3000. a new Excellon.
  3001. :return: None
  3002. """
  3003. self.defaults.report_usage("on_edit_join_exc()")
  3004. objs = self.collection.get_selected()
  3005. for obj in objs:
  3006. if not isinstance(obj, ExcellonObject):
  3007. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3008. return
  3009. if len(objs) < 2:
  3010. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3011. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3012. return 'fail'
  3013. def initialize(exc_obj, app):
  3014. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3015. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3016. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3017. self.should_we_save = True
  3018. def on_edit_join_grb(self):
  3019. """
  3020. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3021. a new Gerber object.
  3022. :return: None
  3023. """
  3024. self.defaults.report_usage("on_edit_join_grb()")
  3025. objs = self.collection.get_selected()
  3026. for obj in objs:
  3027. if not isinstance(obj, GerberObject):
  3028. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3029. return
  3030. if len(objs) < 2:
  3031. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3032. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3033. return 'fail'
  3034. def initialize(grb_obj, app):
  3035. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3036. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3037. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3038. self.should_we_save = True
  3039. def on_convert_singlegeo_to_multigeo(self):
  3040. """
  3041. Called for converting a Geometry object from single-geo to multi-geo.
  3042. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3043. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3044. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3045. the solid-geometry of that tool.
  3046. :return: None
  3047. """
  3048. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3049. obj = self.collection.get_active()
  3050. if obj is None:
  3051. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3052. return
  3053. if not isinstance(obj, GeometryObject):
  3054. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3055. return
  3056. obj.multigeo = True
  3057. for tooluid, dict_value in obj.tools.items():
  3058. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3059. if not isinstance(obj.solid_geometry, list):
  3060. obj.solid_geometry = [obj.solid_geometry]
  3061. # obj.solid_geometry[:] = []
  3062. obj.plot()
  3063. self.should_we_save = True
  3064. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3065. def on_convert_multigeo_to_singlegeo(self):
  3066. """
  3067. Called for converting a Geometry object from multi-geo to single-geo.
  3068. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3069. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3070. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3071. the solid-geometry of that tool.
  3072. :return: None
  3073. """
  3074. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3075. obj = self.collection.get_active()
  3076. if obj is None:
  3077. self.inform.emit('[ERROR_NOTCL] %s' %
  3078. _("Failed. Select a Geometry Object and try again."))
  3079. return
  3080. if not isinstance(obj, GeometryObject):
  3081. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3082. (_("Expected a GeometryObject, got"), type(obj)))
  3083. return
  3084. obj.multigeo = False
  3085. total_solid_geometry = []
  3086. for tooluid, dict_value in obj.tools.items():
  3087. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3088. # clear the original geometry
  3089. dict_value['solid_geometry'][:] = []
  3090. obj.solid_geometry = deepcopy(total_solid_geometry)
  3091. obj.plot()
  3092. self.should_we_save = True
  3093. self.inform.emit('[success] %s' %
  3094. _("A Geometry object was converted to SingleGeo type."))
  3095. def on_defaults_dict_change(self, field):
  3096. """
  3097. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3098. Edit -> Preferences tab window.
  3099. :param field: the key of the self.defaults dictionary that was changed.
  3100. :return: None
  3101. """
  3102. self.preferencesUiManager.defaults_write_form_field(field=field)
  3103. if field == "units":
  3104. self.set_screen_units(self.defaults['units'])
  3105. def set_screen_units(self, units):
  3106. """
  3107. Set the FlatCAM units on the status bar.
  3108. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3109. :return: None
  3110. """
  3111. self.ui.units_label.setText("[" + units.lower() + "]")
  3112. def on_toggle_units_click(self):
  3113. try:
  3114. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3115. except (TypeError, AttributeError):
  3116. pass
  3117. if self.defaults["units"] == 'MM':
  3118. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3119. else:
  3120. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3121. self.on_toggle_units(no_pref=True)
  3122. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3123. lambda: self.on_toggle_units(no_pref=False))
  3124. def on_toggle_units(self, no_pref=False):
  3125. """
  3126. Callback for the Units radio-button change in the Preferences tab.
  3127. Changes the application's default units adn for the project too.
  3128. If changing the project's units, the change propagates to all of
  3129. the objects in the project.
  3130. :return: None
  3131. """
  3132. self.defaults.report_usage("on_toggle_units")
  3133. if self.toggle_units_ignore:
  3134. return
  3135. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3136. # If option is the same, then ignore
  3137. if new_units == self.defaults["units"].upper():
  3138. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3139. return
  3140. # Keys in self.defaults for which to scale their values
  3141. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3142. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "tools_iso_tool_vtipdia",
  3143. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3144. "gerber_editor_ma_high",
  3145. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3146. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3147. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3148. "excellon_feedrate_probe", "excellon_milling_dia",
  3149. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3150. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3151. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3152. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3153. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3154. "geometry_extracut_length", "geometry_z_pdepth",
  3155. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3156. 'cncjob_tooldia',
  3157. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3158. "tools_paintnewdia",
  3159. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3160. "tools_nccnewdia", "tools_ncc_offset_value",
  3161. "tools_2sided_drilldia",
  3162. "tools_film_boundary", "tools_film_scale_stroke",
  3163. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3164. "tools_cutout_depthperpass",
  3165. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3166. "tools_panelize_spacing_rows",
  3167. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3168. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3169. "tools_transform_buffer_dis",
  3170. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3171. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3172. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3173. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3174. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3175. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3176. "tools_cr_h2h_val", "tools_cr_dh_val",
  3177. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3178. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3179. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3180. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3181. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3182. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3183. "tools_copper_thieving_mask_clearance",
  3184. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3185. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3186. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3187. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3188. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3189. "tools_invert_margin",
  3190. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3191. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3192. def scale_defaults(sfactor):
  3193. for dim in dimensions:
  3194. if dim in [
  3195. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3196. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3197. 'tools_transform_mirror_point'
  3198. ]:
  3199. if self.defaults[dim] is None or self.defaults[dim] == '':
  3200. continue
  3201. try:
  3202. coordinates = self.defaults[dim].split(",")
  3203. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3204. coords_xy[0] *= sfactor
  3205. coords_xy[1] *= sfactor
  3206. self.defaults[dim] = "%.*f, %.*f" % (
  3207. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3208. except Exception as e:
  3209. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3210. elif dim in [
  3211. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3212. ]:
  3213. if self.defaults[dim] is None or self.defaults[dim] == '':
  3214. continue
  3215. try:
  3216. self.defaults[dim] = float(self.defaults[dim])
  3217. tools_diameters = [self.defaults[dim]]
  3218. except ValueError:
  3219. try:
  3220. tools_string = self.defaults[dim].split(",")
  3221. tools_diameters = [eval(a) for a in tools_string if a != '']
  3222. except Exception as e:
  3223. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3224. continue
  3225. self.defaults[dim] = ''
  3226. td_len = len(tools_diameters)
  3227. if td_len > 1:
  3228. for t in range(td_len):
  3229. tools_diameters[t] *= sfactor
  3230. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3231. else:
  3232. tools_diameters[0] *= sfactor
  3233. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3234. elif dim in ['global_gridx', 'global_gridy']:
  3235. # format the number of decimals to the one specified in self.decimals
  3236. try:
  3237. val = float(self.defaults[dim]) * sfactor
  3238. except Exception as e:
  3239. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3240. continue
  3241. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3242. else:
  3243. # the number of decimals for the rest is kept unchanged
  3244. if self.defaults[dim]:
  3245. try:
  3246. val = float(self.defaults[dim]) * sfactor
  3247. except Exception as e:
  3248. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3249. continue
  3250. self.defaults[dim] = val
  3251. # The scaling factor depending on choice of units.
  3252. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3253. # Changing project units. Warn user.
  3254. msgbox = QtWidgets.QMessageBox()
  3255. msgbox.setWindowTitle(_("Toggle Units"))
  3256. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3257. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3258. msgbox.setText(_("Changing the units of the project\n"
  3259. "will scale all objects.\n\n"
  3260. "Do you want to continue?"))
  3261. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3262. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3263. msgbox.setDefaultButton(bt_ok)
  3264. msgbox.exec_()
  3265. response = msgbox.clickedButton()
  3266. if response == bt_ok:
  3267. if no_pref is False:
  3268. self.preferencesUiManager.defaults_read_form()
  3269. scale_defaults(factor)
  3270. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3271. self.defaults["units"] = new_units
  3272. # update the defaults from form, some may assume that the conversion is enough and it's not
  3273. self.on_options_app2project()
  3274. # update the objects
  3275. for obj in self.collection.get_list():
  3276. obj.convert_units(new_units)
  3277. # make that the properties stored in the object are also updated
  3278. self.app_obj.object_changed.emit(obj)
  3279. # rebuild the object UI
  3280. obj.build_ui()
  3281. # change this only if the workspace is active
  3282. if self.defaults['global_workspace'] is True:
  3283. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3284. # adjust the grid values on the main toolbar
  3285. val_x = float(self.defaults['global_gridx']) * factor
  3286. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3287. current = self.collection.get_active()
  3288. if current is not None:
  3289. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3290. if not isinstance(current, GeometryObject):
  3291. current.to_form()
  3292. # replot all objects
  3293. self.plot_all()
  3294. # set the status labels to reflect the current FlatCAM units
  3295. self.set_screen_units(new_units)
  3296. # signal to the app that we changed the object properties and it should save the project
  3297. self.should_we_save = True
  3298. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3299. else:
  3300. # Undo toggling
  3301. self.toggle_units_ignore = True
  3302. if self.defaults['units'].upper() == 'MM':
  3303. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3304. else:
  3305. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3306. self.toggle_units_ignore = False
  3307. # store the grid values so they are not changed in the next step
  3308. val_x = float(self.defaults['global_gridx'])
  3309. val_y = float(self.defaults['global_gridy'])
  3310. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3311. self.preferencesUiManager.defaults_read_form()
  3312. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3313. # in self.defaults from the GUI elements but
  3314. # I don't want it for the grid values, so I update them here
  3315. self.defaults['global_gridx'] = val_x
  3316. self.defaults['global_gridy'] = val_y
  3317. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3318. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3319. def on_toggle_axis(self):
  3320. self.defaults.report_usage("on_toggle_axis()")
  3321. if self.toggle_axis is False:
  3322. if self.is_legacy is False:
  3323. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3324. parent=self.plotcanvas.view.scene)
  3325. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3326. parent=self.plotcanvas.view.scene)
  3327. else:
  3328. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3329. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3330. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3331. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3332. self.plotcanvas.canvas.draw()
  3333. self.inform.emit(_("Axis enabled."))
  3334. self.toggle_axis = True
  3335. else:
  3336. if self.is_legacy is False:
  3337. self.plotcanvas.v_line.parent = None
  3338. self.plotcanvas.h_line.parent = None
  3339. else:
  3340. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3341. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3342. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3343. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3344. self.plotcanvas.canvas.draw()
  3345. self.inform.emit(_("Axis disabled."))
  3346. self.toggle_axis = False
  3347. def on_toggle_hud(self):
  3348. new_state = False if self.plotcanvas.hud_enabled else True
  3349. self.plotcanvas.on_toggle_hud(state=new_state)
  3350. if new_state is False:
  3351. self.inform.emit(_("HUD disabled."))
  3352. else:
  3353. self.inform.emit(_("HUD enabled."))
  3354. def on_toggle_grid_lines(self):
  3355. self.defaults.report_usage("on_toggle_grd_lines()")
  3356. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3357. if tt_settings.contains("theme"):
  3358. theme = tt_settings.value('theme', type=str)
  3359. else:
  3360. theme = 'white'
  3361. if self.toggle_grid_lines is False:
  3362. if self.is_legacy is False:
  3363. if theme == 'white':
  3364. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3365. else:
  3366. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3367. else:
  3368. self.plotcanvas.axes.grid(True)
  3369. try:
  3370. self.plotcanvas.canvas.draw()
  3371. except IndexError:
  3372. pass
  3373. pass
  3374. self.inform.emit(_("Grid enabled."))
  3375. self.toggle_grid_lines = True
  3376. else:
  3377. if self.is_legacy is False:
  3378. if theme == 'white':
  3379. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3380. else:
  3381. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3382. else:
  3383. self.plotcanvas.axes.grid(False)
  3384. try:
  3385. self.plotcanvas.canvas.draw()
  3386. except IndexError:
  3387. pass
  3388. self.toggle_grid_lines = False
  3389. self.inform.emit(_("Grid disabled."))
  3390. if self.is_legacy is False:
  3391. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3392. # - perhaps is a bug in VisPy implementation
  3393. if self.grid_status():
  3394. self.app_cursor.enabled = False
  3395. self.app_cursor.enabled = True
  3396. else:
  3397. self.app_cursor.enabled = True
  3398. self.app_cursor.enabled = False
  3399. def on_tab_rmb_click(self, checked):
  3400. self.ui.notebook.set_detachable(val=checked)
  3401. self.defaults["global_tabs_detachable"] = checked
  3402. self.ui.plot_tab_area.set_detachable(val=checked)
  3403. self.defaults["global_tabs_detachable"] = checked
  3404. def on_tab_setup_context_menu(self):
  3405. initial_checked = self.defaults["global_tabs_detachable"]
  3406. action_name = str(_("Detachable Tabs"))
  3407. action = QtWidgets.QAction(self)
  3408. action.setCheckable(True)
  3409. action.setText(action_name)
  3410. action.setChecked(initial_checked)
  3411. self.ui.notebook.tabBar.addAction(action)
  3412. self.ui.plot_tab_area.tabBar.addAction(action)
  3413. try:
  3414. action.triggered.disconnect()
  3415. except TypeError:
  3416. pass
  3417. action.triggered.connect(self.on_tab_rmb_click)
  3418. def on_deselect_all(self):
  3419. self.collection.set_all_inactive()
  3420. self.delete_selection_shape()
  3421. def on_workspace_modified(self):
  3422. # self.save_defaults(silent=True)
  3423. self.plotcanvas.delete_workspace()
  3424. self.preferencesUiManager.defaults_read_form()
  3425. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3426. def on_workspace(self):
  3427. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3428. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3429. self.inform.emit(_("Workspace enabled."))
  3430. else:
  3431. self.plotcanvas.delete_workspace()
  3432. self.inform.emit(_("Workspace disabled."))
  3433. self.preferencesUiManager.defaults_read_form()
  3434. # self.save_defaults(silent=True)
  3435. def on_workspace_toggle(self):
  3436. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3437. try:
  3438. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3439. except TypeError:
  3440. pass
  3441. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3442. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3443. self.on_workspace()
  3444. def on_cursor_type(self, val):
  3445. """
  3446. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3447. :return: None
  3448. """
  3449. self.app_cursor.enabled = False
  3450. if val == 'small':
  3451. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3452. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3453. self.app_cursor = self.plotcanvas.new_cursor()
  3454. else:
  3455. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3456. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3457. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3458. if self.ui.grid_snap_btn.isChecked():
  3459. self.app_cursor.enabled = True
  3460. else:
  3461. self.app_cursor.enabled = False
  3462. def on_tool_add_keypress(self):
  3463. # ## Current application units in Upper Case
  3464. self.units = self.defaults['units'].upper()
  3465. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3466. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3467. if notebook_widget_name == 'selected_tab':
  3468. if self.collection.get_active().kind == 'geometry':
  3469. # Tool add works for Geometry only if Advanced is True in Preferences
  3470. if self.defaults["global_app_level"] == 'a':
  3471. tool_add_popup = FCInputDialog(title="New Tool ...",
  3472. text='Enter a Tool Diameter:',
  3473. min=0.0000, max=99.9999, decimals=4)
  3474. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3475. val, ok = tool_add_popup.get_value()
  3476. if ok:
  3477. if float(val) == 0:
  3478. self.inform.emit('[WARNING_NOTCL] %s' %
  3479. _("Please enter a tool diameter with non-zero value, in Float format."))
  3480. return
  3481. self.collection.get_active().on_tool_add(dia=float(val))
  3482. else:
  3483. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3484. else:
  3485. msgbox = QtWidgets.QMessageBox()
  3486. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3487. "Go to Preferences -> General - Show Advanced Options."))
  3488. msgbox.setWindowTitle("Tool adding ...")
  3489. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3490. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3491. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3492. msgbox.setDefaultButton(bt_ok)
  3493. msgbox.exec_()
  3494. # work only if the notebook tab on focus is the Tools_Tab
  3495. if notebook_widget_name == 'tool_tab':
  3496. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3497. # and only if the tool is NCC Tool
  3498. if tool_widget == self.ncclear_tool.toolName:
  3499. self.ncclear_tool.on_add_tool_by_key()
  3500. # and only if the tool is Paint Area Tool
  3501. elif tool_widget == self.paint_tool.toolName:
  3502. self.paint_tool.on_add_tool_by_key()
  3503. # and only if the tool is Solder Paste Dispensing Tool
  3504. elif tool_widget == self.paste_tool.toolName:
  3505. self.paste_tool.on_add_tool_by_key()
  3506. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3507. # See description below.
  3508. def on_delete_keypress(self):
  3509. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3510. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3511. if notebook_widget_name == 'selected_tab':
  3512. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3513. self.collection.get_active().on_tool_delete()
  3514. # work only if the notebook tab on focus is the Tools_Tab
  3515. elif notebook_widget_name == 'tool_tab':
  3516. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3517. # and only if the tool is NCC Tool
  3518. if tool_widget == self.ncclear_tool.toolName:
  3519. self.ncclear_tool.on_tool_delete()
  3520. # and only if the tool is Paint Tool
  3521. elif tool_widget == self.paint_tool.toolName:
  3522. self.paint_tool.on_tool_delete()
  3523. # and only if the tool is Solder Paste Dispensing Tool
  3524. elif tool_widget == self.paste_tool.toolName:
  3525. self.paste_tool.on_tool_delete()
  3526. else:
  3527. self.on_delete()
  3528. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3529. # some screens you have to be careful where you hover with your mouse.
  3530. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3531. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3532. # Complicated, I know :)
  3533. def on_delete(self, force_deletion=False):
  3534. """
  3535. Delete the currently selected FlatCAMObjs.
  3536. :param force_deletion: used by Tcl command
  3537. :return: None
  3538. """
  3539. self.defaults.report_usage("on_delete()")
  3540. response = None
  3541. bt_ok = None
  3542. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3543. # a geometry object before we update it.
  3544. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3545. and self.grb_editor.editor_active is False:
  3546. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3547. msgbox = QtWidgets.QMessageBox()
  3548. msgbox.setWindowTitle(_("Delete objects"))
  3549. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3550. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3551. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3552. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3553. "the selected objects?"))
  3554. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3555. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3556. msgbox.setDefaultButton(bt_ok)
  3557. msgbox.exec_()
  3558. response = msgbox.clickedButton()
  3559. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3560. response = bt_ok
  3561. if response == bt_ok:
  3562. if self.collection.get_active():
  3563. self.log.debug("App.on_delete()")
  3564. for obj_active in self.collection.get_selected():
  3565. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3566. if obj_active.kind == 'gerber':
  3567. for el in obj_active.mark_shapes:
  3568. obj_active.mark_shapes[el].clear(update=True)
  3569. obj_active.mark_shapes[el].enabled = False
  3570. # obj_active.mark_shapes[el] = None
  3571. del el
  3572. elif isinstance(obj_active, CNCJobObject):
  3573. try:
  3574. obj_active.text_col.enabled = False
  3575. del obj_active.text_col
  3576. obj_active.annotation.clear(update=True)
  3577. del obj_active.annotation
  3578. except AttributeError as e:
  3579. log.debug(
  3580. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3581. )
  3582. while self.collection.get_selected():
  3583. self.delete_first_selected()
  3584. self.inform.emit('%s...' % _("Object(s) deleted"))
  3585. # make sure that the selection shape is deleted, too
  3586. self.delete_selection_shape()
  3587. # if there are no longer objects delete also the exclusion areas shapes
  3588. if not self.collection.get_list():
  3589. self.exc_areas.clear_shapes()
  3590. else:
  3591. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3592. else:
  3593. self.inform.emit(_("Save the work in Editor and try again ..."))
  3594. def delete_first_selected(self):
  3595. # Keep this for later
  3596. try:
  3597. sel_obj = self.collection.get_active()
  3598. name = sel_obj.options["name"]
  3599. isPlotted = sel_obj.options["plot"]
  3600. except AttributeError:
  3601. self.log.debug("Nothing selected for deletion")
  3602. return
  3603. if self.is_legacy is True:
  3604. # Remove plot only if the object was plotted otherwise delaxes will fail
  3605. if isPlotted:
  3606. try:
  3607. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3608. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3609. except Exception as e:
  3610. log.debug("App.delete_first_selected() --> %s" % str(e))
  3611. self.plotcanvas.auto_adjust_axes()
  3612. # Remove from dictionary
  3613. self.collection.delete_active()
  3614. # Clear form
  3615. self.setup_component_editor()
  3616. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3617. def on_set_origin(self):
  3618. """
  3619. Set the origin to the left mouse click position
  3620. :return: None
  3621. """
  3622. # display the message for the user
  3623. # and ask him to click on the desired position
  3624. self.defaults.report_usage("on_set_origin()")
  3625. def origin_replot():
  3626. def worker_task():
  3627. with self.proc_container.new('%s...' % _("Plotting")):
  3628. for obj in self.collection.get_list():
  3629. obj.plot()
  3630. self.plotcanvas.fit_view()
  3631. if self.is_legacy:
  3632. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3633. else:
  3634. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3635. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3636. self.inform.emit(_('Click to set the origin ...'))
  3637. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3638. # first disconnect it as it may have been used by something else
  3639. try:
  3640. self.replot_signal.disconnect()
  3641. except TypeError:
  3642. pass
  3643. self.replot_signal[list].connect(origin_replot)
  3644. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3645. """
  3646. :param event:
  3647. :param location:
  3648. :param noplot:
  3649. :param use_thread:
  3650. :return:
  3651. """
  3652. noplot_sig = noplot
  3653. def worker_task():
  3654. with self.proc_container.new(_("Setting Origin...")):
  3655. obj_list = self.collection.get_list()
  3656. for obj in obj_list:
  3657. obj.offset((x, y))
  3658. self.app_obj.object_changed.emit(obj)
  3659. # Update the object bounding box options
  3660. a, b, c, d = obj.bounds()
  3661. obj.options['xmin'] = a
  3662. obj.options['ymin'] = b
  3663. obj.options['xmax'] = c
  3664. obj.options['ymax'] = d
  3665. self.inform.emit('[success] %s...' % _('Origin set'))
  3666. for obj in obj_list:
  3667. out_name = obj.options["name"]
  3668. if obj.kind == 'gerber':
  3669. obj.source_file = self.export_gerber(
  3670. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3671. elif obj.kind == 'excellon':
  3672. obj.source_file = self.export_excellon(
  3673. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3674. if noplot_sig is False:
  3675. self.replot_signal.emit([])
  3676. if location is not None:
  3677. if len(location) != 2:
  3678. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3679. return 'fail'
  3680. x, y = location
  3681. if use_thread is True:
  3682. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3683. else:
  3684. worker_task()
  3685. self.should_we_save = True
  3686. return
  3687. if event is not None and event.button == 1:
  3688. if self.is_legacy is False:
  3689. event_pos = event.pos
  3690. else:
  3691. event_pos = (event.xdata, event.ydata)
  3692. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3693. if self.grid_status():
  3694. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3695. else:
  3696. pos = pos_canvas
  3697. x = 0 - pos[0]
  3698. y = 0 - pos[1]
  3699. if use_thread is True:
  3700. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3701. else:
  3702. worker_task()
  3703. self.should_we_save = True
  3704. def on_move2origin(self, use_thread=True):
  3705. """
  3706. Move selected objects to origin.
  3707. :param use_thread: Control if to use threaded operation. Boolean.
  3708. :return:
  3709. """
  3710. def worker_task():
  3711. with self.proc_container.new(_("Moving to Origin...")):
  3712. obj_list = self.collection.get_selected()
  3713. if not obj_list:
  3714. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3715. return
  3716. xminlist = []
  3717. yminlist = []
  3718. # first get a bounding box to fit all
  3719. for obj in obj_list:
  3720. xmin, ymin, xmax, ymax = obj.bounds()
  3721. xminlist.append(xmin)
  3722. yminlist.append(ymin)
  3723. # get the minimum x,y for all objects selected
  3724. x = min(xminlist)
  3725. y = min(yminlist)
  3726. for obj in obj_list:
  3727. obj.offset((-x, -y))
  3728. self.app_obj.object_changed.emit(obj)
  3729. # Update the object bounding box options
  3730. a, b, c, d = obj.bounds()
  3731. obj.options['xmin'] = a
  3732. obj.options['ymin'] = b
  3733. obj.options['xmax'] = c
  3734. obj.options['ymax'] = d
  3735. for obj in obj_list:
  3736. obj.plot()
  3737. for obj in obj_list:
  3738. out_name = obj.options["name"]
  3739. if obj.kind == 'gerber':
  3740. obj.source_file = self.export_gerber(
  3741. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3742. elif obj.kind == 'excellon':
  3743. obj.source_file = self.export_excellon(
  3744. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3745. self.inform.emit('[success] %s...' % _('Origin set'))
  3746. if use_thread is True:
  3747. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3748. else:
  3749. worker_task()
  3750. self.should_we_save = True
  3751. def on_jump_to(self, custom_location=None, fit_center=True):
  3752. """
  3753. Jump to a location by setting the mouse cursor location.
  3754. :param custom_location: Jump to a specified point. (x, y) tuple.
  3755. :param fit_center: If to fit view. Boolean.
  3756. :return:
  3757. """
  3758. self.defaults.report_usage("on_jump_to()")
  3759. if not custom_location:
  3760. dia_box_location = None
  3761. try:
  3762. dia_box_location = eval(self.clipboard.text())
  3763. except Exception:
  3764. pass
  3765. if type(dia_box_location) == tuple:
  3766. dia_box_location = str(dia_box_location)
  3767. else:
  3768. dia_box_location = None
  3769. # dia_box = Dialog_box(title=_("Jump to ..."),
  3770. # label=_("Enter the coordinates in format X,Y:"),
  3771. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3772. # initial_text=dia_box_location)
  3773. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3774. label=_("Enter the coordinates in format X,Y:"),
  3775. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3776. initial_text=dia_box_location,
  3777. reference=self.defaults['global_jump_ref'])
  3778. if dia_box.ok is True:
  3779. try:
  3780. location = eval(dia_box.location)
  3781. if not isinstance(location, tuple):
  3782. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3783. return
  3784. if dia_box.reference == 'rel':
  3785. rel_x = self.mouse[0] + location[0]
  3786. rel_y = self.mouse[1] + location[1]
  3787. location = (rel_x, rel_y)
  3788. self.defaults['global_jump_ref'] = dia_box.reference
  3789. except Exception:
  3790. return
  3791. else:
  3792. return
  3793. else:
  3794. location = custom_location
  3795. self.jump_signal.emit(location)
  3796. if fit_center:
  3797. self.plotcanvas.fit_center(loc=location)
  3798. cursor = QtGui.QCursor()
  3799. if self.is_legacy is False:
  3800. # I don't know where those differences come from but they are constant for the current
  3801. # execution of the application and they are multiples of a value around 0.0263mm.
  3802. # In a random way sometimes they are more sometimes they are less
  3803. # if units == 'MM':
  3804. # cal_factor = 0.0263
  3805. # else:
  3806. # cal_factor = 0.0263 / 25.4
  3807. cal_location = (location[0], location[1])
  3808. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3809. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3810. j_pos = (
  3811. int(canvas_origin.x() + round(jump_loc[0])),
  3812. int(canvas_origin.y() + round(jump_loc[1]))
  3813. )
  3814. cursor.setPos(j_pos[0], j_pos[1])
  3815. else:
  3816. # find the canvas origin which is in the top left corner
  3817. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3818. # determine the coordinates for the lowest left point of the canvas
  3819. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3820. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3821. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3822. # canvas) and the point (width, height) is in the top-right location
  3823. loc = self.plotcanvas.axes.transData.transform_point(location)
  3824. j_pos = (
  3825. int(x0 + loc[0]),
  3826. int(y0 - loc[1])
  3827. )
  3828. cursor.setPos(j_pos[0], j_pos[1])
  3829. self.plotcanvas.mouse = [location[0], location[1]]
  3830. if self.defaults["global_cursor_color_enabled"] is True:
  3831. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3832. else:
  3833. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3834. if self.grid_status():
  3835. # Update cursor
  3836. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3837. symbol='++', edge_color=self.cursor_color_3D,
  3838. edge_width=self.defaults["global_cursor_width"],
  3839. size=self.defaults["global_cursor_size"])
  3840. # Set the relative position label
  3841. dx = location[0] - float(self.rel_point1[0])
  3842. dy = location[1] - float(self.rel_point1[1])
  3843. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3844. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3845. # # Set the position label
  3846. #
  3847. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3848. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3849. units = self.defaults["units"].lower()
  3850. self.plotcanvas.text_hud.text = \
  3851. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3852. dx, units, dy, units, location[0], units, location[1], units)
  3853. self.inform.emit('[success] %s' % _("Done."))
  3854. return location
  3855. def on_locate(self, obj, fit_center=True):
  3856. """
  3857. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3858. :param obj: The object on which to locate certain points
  3859. :param fit_center: If to fit view. Boolean.
  3860. :return: A point location. (x, y) tuple.
  3861. """
  3862. self.defaults.report_usage("on_locate()")
  3863. if obj is None:
  3864. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3865. return 'fail'
  3866. class DialogBoxChoice(QtWidgets.QDialog):
  3867. def __init__(self, title=None, icon=None, choice='bl'):
  3868. """
  3869. :param title: string with the window title
  3870. """
  3871. super(DialogBoxChoice, self).__init__()
  3872. self.ok = False
  3873. self.setWindowIcon(icon)
  3874. self.setWindowTitle(str(title))
  3875. self.form = QtWidgets.QFormLayout(self)
  3876. self.ref_radio = RadioSet([
  3877. {"label": _("Bottom-Left"), "value": "bl"},
  3878. {"label": _("Top-Left"), "value": "tl"},
  3879. {"label": _("Bottom-Right"), "value": "br"},
  3880. {"label": _("Top-Right"), "value": "tr"},
  3881. {"label": _("Center"), "value": "c"}
  3882. ], orientation='vertical', stretch=False)
  3883. self.ref_radio.set_value(choice)
  3884. self.form.addRow(self.ref_radio)
  3885. self.button_box = QtWidgets.QDialogButtonBox(
  3886. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3887. Qt.Horizontal, parent=self)
  3888. self.form.addRow(self.button_box)
  3889. self.button_box.accepted.connect(self.accept)
  3890. self.button_box.rejected.connect(self.reject)
  3891. if self.exec_() == QtWidgets.QDialog.Accepted:
  3892. self.ok = True
  3893. self.location_point = self.ref_radio.get_value()
  3894. else:
  3895. self.ok = False
  3896. self.location_point = None
  3897. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3898. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3899. choice=self.defaults['global_locate_pt'])
  3900. if dia_box.ok is True:
  3901. try:
  3902. location_point = dia_box.location_point
  3903. self.defaults['global_locate_pt'] = dia_box.location_point
  3904. except Exception:
  3905. return
  3906. else:
  3907. return
  3908. loc_b = obj.bounds()
  3909. if location_point == 'bl':
  3910. location = (loc_b[0], loc_b[1])
  3911. elif location_point == 'tl':
  3912. location = (loc_b[0], loc_b[3])
  3913. elif location_point == 'br':
  3914. location = (loc_b[2], loc_b[1])
  3915. elif location_point == 'tr':
  3916. location = (loc_b[2], loc_b[3])
  3917. else:
  3918. # center
  3919. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3920. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3921. location = (cx, cy)
  3922. self.locate_signal.emit(location, location_point)
  3923. if fit_center:
  3924. self.plotcanvas.fit_center(loc=location)
  3925. cursor = QtGui.QCursor()
  3926. if self.is_legacy is False:
  3927. # I don't know where those differences come from but they are constant for the current
  3928. # execution of the application and they are multiples of a value around 0.0263mm.
  3929. # In a random way sometimes they are more sometimes they are less
  3930. # if units == 'MM':
  3931. # cal_factor = 0.0263
  3932. # else:
  3933. # cal_factor = 0.0263 / 25.4
  3934. cal_location = (location[0], location[1])
  3935. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3936. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3937. j_pos = (
  3938. int(canvas_origin.x() + round(jump_loc[0])),
  3939. int(canvas_origin.y() + round(jump_loc[1]))
  3940. )
  3941. cursor.setPos(j_pos[0], j_pos[1])
  3942. else:
  3943. # find the canvas origin which is in the top left corner
  3944. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3945. # determine the coordinates for the lowest left point of the canvas
  3946. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3947. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3948. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3949. # canvas) and the point (width, height) is in the top-right location
  3950. loc = self.plotcanvas.axes.transData.transform_point(location)
  3951. j_pos = (
  3952. int(x0 + loc[0]),
  3953. int(y0 - loc[1])
  3954. )
  3955. cursor.setPos(j_pos[0], j_pos[1])
  3956. self.plotcanvas.mouse = [location[0], location[1]]
  3957. if self.defaults["global_cursor_color_enabled"] is True:
  3958. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3959. else:
  3960. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3961. if self.grid_status():
  3962. # Update cursor
  3963. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3964. symbol='++', edge_color=self.cursor_color_3D,
  3965. edge_width=self.defaults["global_cursor_width"],
  3966. size=self.defaults["global_cursor_size"])
  3967. # Set the relative position label
  3968. self.dx = location[0] - float(self.rel_point1[0])
  3969. self.dy = location[1] - float(self.rel_point1[1])
  3970. # Set the position label
  3971. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3972. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3973. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3974. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3975. units = self.defaults["units"].lower()
  3976. self.plotcanvas.text_hud.text = \
  3977. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3978. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3979. self.inform.emit('[success] %s' % _("Done."))
  3980. return location
  3981. def on_copy_command(self):
  3982. """
  3983. Will copy a selection of objects, creating new objects.
  3984. :return:
  3985. """
  3986. self.defaults.report_usage("on_copy_command()")
  3987. def initialize(obj_init, app):
  3988. """
  3989. :param obj_init: the new object
  3990. :type obj_init: class
  3991. :param app: An instance of the App class
  3992. :type app: App
  3993. :return: None
  3994. :rtype:
  3995. """
  3996. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3997. try:
  3998. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3999. except AttributeError:
  4000. pass
  4001. try:
  4002. obj_init.apertures = deepcopy(obj.apertures)
  4003. except AttributeError:
  4004. pass
  4005. try:
  4006. if obj.tools:
  4007. obj_init.tools = deepcopy(obj.tools)
  4008. except Exception as err:
  4009. log.debug("App.on_copy_command() --> %s" % str(err))
  4010. try:
  4011. obj_init.source_file = deepcopy(obj.source_file)
  4012. except (AttributeError, TypeError):
  4013. pass
  4014. def initialize_excellon(obj_init, app):
  4015. obj_init.source_file = deepcopy(obj.source_file)
  4016. obj_init.tools = deepcopy(obj.tools)
  4017. # drills are offset, so they need to be deep copied
  4018. obj_init.drills = deepcopy(obj.drills)
  4019. # slots are offset, so they need to be deep copied
  4020. obj_init.slots = deepcopy(obj.slots)
  4021. obj_init.create_geometry()
  4022. def initialize_script(obj_init, app_obj):
  4023. obj_init.source_file = deepcopy(obj.source_file)
  4024. def initialize_document(obj_init, app_obj):
  4025. obj_init.source_file = deepcopy(obj.source_file)
  4026. for obj in self.collection.get_selected():
  4027. obj_name = obj.options["name"]
  4028. try:
  4029. if isinstance(obj, ExcellonObject):
  4030. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4031. elif isinstance(obj, GerberObject):
  4032. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4033. elif isinstance(obj, GeometryObject):
  4034. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4035. elif isinstance(obj, ScriptObject):
  4036. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4037. elif isinstance(obj, DocumentObject):
  4038. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4039. except Exception as e:
  4040. return "Operation failed: %s" % str(e)
  4041. def on_copy_object2(self, custom_name):
  4042. def initialize_geometry(obj_init, app):
  4043. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4044. try:
  4045. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4046. except AttributeError:
  4047. pass
  4048. try:
  4049. obj_init.apertures = deepcopy(obj.apertures)
  4050. except AttributeError:
  4051. pass
  4052. try:
  4053. if obj.tools:
  4054. obj_init.tools = deepcopy(obj.tools)
  4055. except Exception as ee:
  4056. log.debug("on_copy_object2() --> %s" % str(ee))
  4057. def initialize_gerber(obj_init, app):
  4058. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4059. obj_init.apertures = deepcopy(obj.apertures)
  4060. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4061. def initialize_excellon(obj_init, app):
  4062. obj_init.tools = deepcopy(obj.tools)
  4063. # drills are offset, so they need to be deep copied
  4064. obj_init.drills = deepcopy(obj.drills)
  4065. # slots are offset, so they need to be deep copied
  4066. obj_init.slots = deepcopy(obj.slots)
  4067. obj_init.create_geometry()
  4068. for obj in self.collection.get_selected():
  4069. obj_name = obj.options["name"]
  4070. try:
  4071. if isinstance(obj, ExcellonObject):
  4072. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4073. elif isinstance(obj, GerberObject):
  4074. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4075. elif isinstance(obj, GeometryObject):
  4076. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4077. except Exception as er:
  4078. return "Operation failed: %s" % str(er)
  4079. def on_rename_object(self, text):
  4080. """
  4081. Will rename an object.
  4082. :param text: New name for the object.
  4083. :return:
  4084. """
  4085. self.defaults.report_usage("on_rename_object()")
  4086. named_obj = self.collection.get_active()
  4087. for obj in named_obj:
  4088. if obj is list:
  4089. self.on_rename_object(text)
  4090. else:
  4091. try:
  4092. obj.options['name'] = text
  4093. except Exception as e:
  4094. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4095. def convert_any2geo(self):
  4096. """
  4097. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4098. :return:
  4099. """
  4100. self.defaults.report_usage("convert_any2geo()")
  4101. def initialize(obj_init, app):
  4102. obj_init.solid_geometry = obj.solid_geometry
  4103. try:
  4104. obj_init.follow_geometry = obj.follow_geometry
  4105. except AttributeError:
  4106. pass
  4107. try:
  4108. obj_init.apertures = obj.apertures
  4109. except AttributeError:
  4110. pass
  4111. try:
  4112. if obj.tools:
  4113. obj_init.tools = obj.tools
  4114. except AttributeError:
  4115. pass
  4116. def initialize_excellon(obj_init, app):
  4117. # objs = self.collection.get_selected()
  4118. # GeometryObject.merge(objs, obj)
  4119. solid_geo = []
  4120. for tool in obj.tools:
  4121. for geo in obj.tools[tool]['solid_geometry']:
  4122. solid_geo.append(geo)
  4123. obj_init.solid_geometry = deepcopy(solid_geo)
  4124. if not self.collection.get_selected():
  4125. log.warning("App.convert_any2geo --> No object selected")
  4126. self.inform.emit('[WARNING_NOTCL] %s' %
  4127. _("No object is selected. Select an object and try again."))
  4128. return
  4129. for obj in self.collection.get_selected():
  4130. obj_name = obj.options["name"]
  4131. try:
  4132. if isinstance(obj, ExcellonObject):
  4133. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4134. else:
  4135. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4136. except Exception as e:
  4137. return "Operation failed: %s" % str(e)
  4138. def convert_any2gerber(self):
  4139. """
  4140. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4141. :return:
  4142. """
  4143. self.defaults.report_usage("convert_any2gerber()")
  4144. def initialize_geometry(obj_init, app):
  4145. apertures = {}
  4146. apid = 0
  4147. apertures[str(apid)] = {}
  4148. apertures[str(apid)]['geometry'] = []
  4149. for obj_orig in obj.solid_geometry:
  4150. new_elem = {}
  4151. new_elem['solid'] = obj_orig
  4152. try:
  4153. new_elem['follow'] = obj_orig.exterior
  4154. except AttributeError:
  4155. pass
  4156. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4157. apertures[str(apid)]['size'] = 0.0
  4158. apertures[str(apid)]['type'] = 'C'
  4159. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4160. obj_init.apertures = deepcopy(apertures)
  4161. def initialize_excellon(obj_init, app):
  4162. apertures = {}
  4163. apid = 10
  4164. for tool in obj.tools:
  4165. apertures[str(apid)] = {}
  4166. apertures[str(apid)]['geometry'] = []
  4167. for geo in obj.tools[tool]['solid_geometry']:
  4168. new_el = {}
  4169. new_el['solid'] = geo
  4170. new_el['follow'] = geo.exterior
  4171. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4172. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4173. apertures[str(apid)]['type'] = 'C'
  4174. apid += 1
  4175. # create solid_geometry
  4176. solid_geometry = []
  4177. for apid in apertures:
  4178. for geo_el in apertures[apid]['geometry']:
  4179. solid_geometry.append(geo_el['solid'])
  4180. solid_geometry = MultiPolygon(solid_geometry)
  4181. solid_geometry = solid_geometry.buffer(0.0000001)
  4182. obj_init.solid_geometry = deepcopy(solid_geometry)
  4183. obj_init.apertures = deepcopy(apertures)
  4184. # clear the working objects (perhaps not necessary due of Python GC)
  4185. apertures.clear()
  4186. if not self.collection.get_selected():
  4187. log.warning("App.convert_any2gerber --> No object selected")
  4188. self.inform.emit('[WARNING_NOTCL] %s' %
  4189. _("No object is selected. Select an object and try again."))
  4190. return
  4191. for obj in self.collection.get_selected():
  4192. obj_name = obj.options["name"]
  4193. try:
  4194. if isinstance(obj, ExcellonObject):
  4195. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4196. elif isinstance(obj, GeometryObject):
  4197. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4198. else:
  4199. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4200. except Exception as e:
  4201. return "Operation failed: %s" % str(e)
  4202. def abort_all_tasks(self):
  4203. """
  4204. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4205. on the first possible occasion.
  4206. :return:
  4207. """
  4208. if self.abort_flag is False:
  4209. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4210. self.abort_flag = True
  4211. self.cleanup.emit()
  4212. def app_is_idle(self):
  4213. if self.abort_flag:
  4214. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4215. self.abort_flag = False
  4216. def on_selectall(self):
  4217. """
  4218. Will draw a selection box shape around the selected objects.
  4219. :return:
  4220. """
  4221. self.defaults.report_usage("on_selectall()")
  4222. # delete the possible selection box around a possible selected object
  4223. self.delete_selection_shape()
  4224. for name in self.collection.get_names():
  4225. self.collection.set_active(name)
  4226. curr_sel_obj = self.collection.get_by_name(name)
  4227. # create the selection box around the selected object
  4228. if self.defaults['global_selection_shape'] is True:
  4229. self.draw_selection_shape(curr_sel_obj)
  4230. def on_preferences(self):
  4231. """
  4232. Adds the Preferences in a Tab in Plot Area
  4233. :return:
  4234. """
  4235. # add the tab if it was closed
  4236. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4237. # delete the absolute and relative position and messages in the infobar
  4238. self.ui.position_label.setText("")
  4239. # self.ui.rel_position_label.setText("")
  4240. # Switch plot_area to preferences page
  4241. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4242. # self.ui.show()
  4243. # detect changes in the preferences
  4244. for idx in range(self.ui.pref_tab_area.count()):
  4245. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4246. try:
  4247. try:
  4248. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4249. except (TypeError, AttributeError):
  4250. pass
  4251. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4252. except AttributeError:
  4253. pass
  4254. try:
  4255. try:
  4256. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4257. except (TypeError, AttributeError):
  4258. pass
  4259. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4260. except AttributeError:
  4261. pass
  4262. try:
  4263. try:
  4264. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4265. except (TypeError, AttributeError):
  4266. pass
  4267. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4268. except AttributeError:
  4269. pass
  4270. try:
  4271. try:
  4272. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4273. except (TypeError, AttributeError):
  4274. pass
  4275. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4276. except AttributeError:
  4277. pass
  4278. try:
  4279. try:
  4280. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4281. except (TypeError, AttributeError):
  4282. pass
  4283. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4284. except AttributeError:
  4285. pass
  4286. def on_tools_database(self, source='app'):
  4287. """
  4288. Adds the Tools Database in a Tab in Plot Area.
  4289. :return:
  4290. """
  4291. for idx in range(self.ui.plot_tab_area.count()):
  4292. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4293. # there can be only one instance of Tools Database at one time
  4294. return
  4295. if source == 'app':
  4296. self.tools_db_tab = ToolsDB2(
  4297. app=self,
  4298. parent=self.ui,
  4299. callback_on_edited=self.on_tools_db_edited,
  4300. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4301. )
  4302. elif source == 'ncc':
  4303. self.tools_db_tab = ToolsDB2(
  4304. app=self,
  4305. parent=self.ui,
  4306. callback_on_edited=self.on_tools_db_edited,
  4307. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4308. )
  4309. elif source == 'paint':
  4310. self.tools_db_tab = ToolsDB2(
  4311. app=self,
  4312. parent=self.ui,
  4313. callback_on_edited=self.on_tools_db_edited,
  4314. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4315. )
  4316. elif source == 'iso':
  4317. self.tools_db_tab = ToolsDB2(
  4318. app=self,
  4319. parent=self.ui,
  4320. callback_on_edited=self.on_tools_db_edited,
  4321. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4322. )
  4323. # add the tab if it was closed
  4324. try:
  4325. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4326. self.tools_db_tab.setObjectName("database_tab")
  4327. except Exception as e:
  4328. log.debug("App.on_tools_database() --> %s" % str(e))
  4329. return
  4330. # delete the absolute and relative position and messages in the infobar
  4331. self.ui.position_label.setText("")
  4332. # self.ui.rel_position_label.setText("")
  4333. # Switch plot_area to preferences page
  4334. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4335. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4336. self.tools_db_tab.ui_connect()
  4337. def on_tools_db_edited(self):
  4338. """
  4339. Executed whenever a tool is edited in Tools Database.
  4340. Will color the text of the Tools Database tab to Red color.
  4341. :return:
  4342. """
  4343. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4344. for idx in range(self.ui.plot_tab_area.count()):
  4345. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4346. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4347. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4348. self.tools_db_changed_flag = True
  4349. def on_geometry_tool_add_from_db_executed(self, tool):
  4350. """
  4351. Here add the tool from DB in the selected geometry object.
  4352. :return:
  4353. """
  4354. tool_from_db = deepcopy(tool)
  4355. obj = self.collection.get_active()
  4356. if isinstance(obj, GeometryObject):
  4357. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4358. # close the tab and delete it
  4359. for idx in range(self.ui.plot_tab_area.count()):
  4360. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4361. wdg = self.ui.plot_tab_area.widget(idx)
  4362. wdg.deleteLater()
  4363. self.ui.plot_tab_area.removeTab(idx)
  4364. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4365. else:
  4366. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4367. def on_plot_area_tab_closed(self, tab_obj_name):
  4368. """
  4369. Executed whenever a QTab is closed in the Plot Area.
  4370. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4371. :return:
  4372. """
  4373. if tab_obj_name == "preferences_tab":
  4374. self.preferencesUiManager.on_close_preferences_tab()
  4375. elif tab_obj_name == "database_tab":
  4376. # disconnect the signals from the table widget in tab
  4377. self.tools_db_tab.ui_disconnect()
  4378. if self.tools_db_changed_flag is True:
  4379. msgbox = QtWidgets.QMessageBox()
  4380. msgbox.setText(_("One or more Tools are edited.\n"
  4381. "Do you want to update the Tools Database?"))
  4382. msgbox.setWindowTitle(_("Save Tools Database"))
  4383. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4384. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4385. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4386. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4387. msgbox.setDefaultButton(bt_yes)
  4388. msgbox.exec_()
  4389. response = msgbox.clickedButton()
  4390. if response == bt_yes:
  4391. self.tools_db_tab.on_save_tools_db()
  4392. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4393. else:
  4394. self.tools_db_changed_flag = False
  4395. self.inform.emit('')
  4396. return
  4397. self.tools_db_tab.deleteLater()
  4398. elif tab_obj_name == "text_editor_tab":
  4399. self.toggle_codeeditor = False
  4400. elif tab_obj_name == "bookmarks_tab":
  4401. self.book_dialog_tab.rebuild_actions()
  4402. self.book_dialog_tab.deleteLater()
  4403. else:
  4404. return
  4405. # def on_plotarea_tab_closed(self, tab_idx):
  4406. # """
  4407. #
  4408. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4409. # :return:
  4410. # """
  4411. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4412. #
  4413. # if widget is not None:
  4414. # widget.deleteLater()
  4415. # self.ui.plot_tab_area.removeTab(tab_idx)
  4416. def on_flipy(self):
  4417. """
  4418. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4419. :return:
  4420. """
  4421. self.defaults.report_usage("on_flipy()")
  4422. obj_list = self.collection.get_selected()
  4423. xminlist = []
  4424. yminlist = []
  4425. xmaxlist = []
  4426. ymaxlist = []
  4427. if not obj_list:
  4428. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4429. else:
  4430. try:
  4431. # first get a bounding box to fit all
  4432. for obj in obj_list:
  4433. xmin, ymin, xmax, ymax = obj.bounds()
  4434. xminlist.append(xmin)
  4435. yminlist.append(ymin)
  4436. xmaxlist.append(xmax)
  4437. ymaxlist.append(ymax)
  4438. # get the minimum x,y and maximum x,y for all objects selected
  4439. xminimal = min(xminlist)
  4440. yminimal = min(yminlist)
  4441. xmaximal = max(xmaxlist)
  4442. ymaximal = max(ymaxlist)
  4443. px = 0.5 * (xminimal + xmaximal)
  4444. py = 0.5 * (yminimal + ymaximal)
  4445. # execute mirroring
  4446. for obj in obj_list:
  4447. obj.mirror('X', [px, py])
  4448. obj.plot()
  4449. self.app_obj.object_changed.emit(obj)
  4450. self.inform.emit('[success] %s' %
  4451. _("Flip on Y axis done."))
  4452. except Exception as e:
  4453. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4454. return
  4455. def on_flipx(self):
  4456. """
  4457. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4458. :return:
  4459. """
  4460. self.defaults.report_usage("on_flipx()")
  4461. obj_list = self.collection.get_selected()
  4462. xminlist = []
  4463. yminlist = []
  4464. xmaxlist = []
  4465. ymaxlist = []
  4466. if not obj_list:
  4467. self.inform.emit('[WARNING_NOTCL] %s' %
  4468. _("No object selected to Flip on X axis."))
  4469. else:
  4470. try:
  4471. # first get a bounding box to fit all
  4472. for obj in obj_list:
  4473. xmin, ymin, xmax, ymax = obj.bounds()
  4474. xminlist.append(xmin)
  4475. yminlist.append(ymin)
  4476. xmaxlist.append(xmax)
  4477. ymaxlist.append(ymax)
  4478. # get the minimum x,y and maximum x,y for all objects selected
  4479. xminimal = min(xminlist)
  4480. yminimal = min(yminlist)
  4481. xmaximal = max(xmaxlist)
  4482. ymaximal = max(ymaxlist)
  4483. px = 0.5 * (xminimal + xmaximal)
  4484. py = 0.5 * (yminimal + ymaximal)
  4485. # execute mirroring
  4486. for obj in obj_list:
  4487. obj.mirror('Y', [px, py])
  4488. obj.plot()
  4489. self.app_obj.object_changed.emit(obj)
  4490. self.inform.emit('[success] %s' %
  4491. _("Flip on X axis done."))
  4492. except Exception as e:
  4493. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4494. return
  4495. def on_rotate(self, silent=False, preset=None):
  4496. """
  4497. Executed when Options -> Rotate Selection menu entry is clicked.
  4498. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4499. :param preset: A value to be used as predefined angle for rotation.
  4500. :return:
  4501. """
  4502. self.defaults.report_usage("on_rotate()")
  4503. obj_list = self.collection.get_selected()
  4504. xminlist = []
  4505. yminlist = []
  4506. xmaxlist = []
  4507. ymaxlist = []
  4508. if not obj_list:
  4509. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4510. else:
  4511. if silent is False:
  4512. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4513. min=-360, max=360, decimals=4,
  4514. init_val=float(self.defaults['tools_transform_rotate']))
  4515. num, ok = rotatebox.get_value()
  4516. else:
  4517. num = preset
  4518. ok = True
  4519. if ok:
  4520. try:
  4521. # first get a bounding box to fit all
  4522. for obj in obj_list:
  4523. xmin, ymin, xmax, ymax = obj.bounds()
  4524. xminlist.append(xmin)
  4525. yminlist.append(ymin)
  4526. xmaxlist.append(xmax)
  4527. ymaxlist.append(ymax)
  4528. # get the minimum x,y and maximum x,y for all objects selected
  4529. xminimal = min(xminlist)
  4530. yminimal = min(yminlist)
  4531. xmaximal = max(xmaxlist)
  4532. ymaximal = max(ymaxlist)
  4533. px = 0.5 * (xminimal + xmaximal)
  4534. py = 0.5 * (yminimal + ymaximal)
  4535. for sel_obj in obj_list:
  4536. sel_obj.rotate(-float(num), point=(px, py))
  4537. sel_obj.plot()
  4538. self.app_obj.object_changed.emit(sel_obj)
  4539. self.inform.emit('[success] %s' % _("Rotation done."))
  4540. except Exception as e:
  4541. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4542. return
  4543. def on_skewx(self):
  4544. """
  4545. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4546. :return:
  4547. """
  4548. self.defaults.report_usage("on_skewx()")
  4549. obj_list = self.collection.get_selected()
  4550. xminlist = []
  4551. yminlist = []
  4552. if not obj_list:
  4553. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4554. else:
  4555. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4556. min=-360, max=360, decimals=4,
  4557. init_val=float(self.defaults['tools_transform_skew_x']))
  4558. num, ok = skewxbox.get_value()
  4559. if ok:
  4560. # first get a bounding box to fit all
  4561. for obj in obj_list:
  4562. xmin, ymin, xmax, ymax = obj.bounds()
  4563. xminlist.append(xmin)
  4564. yminlist.append(ymin)
  4565. # get the minimum x,y and maximum x,y for all objects selected
  4566. xminimal = min(xminlist)
  4567. yminimal = min(yminlist)
  4568. for obj in obj_list:
  4569. obj.skew(num, 0, point=(xminimal, yminimal))
  4570. obj.plot()
  4571. self.app_obj.object_changed.emit(obj)
  4572. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4573. def on_skewy(self):
  4574. """
  4575. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4576. :return:
  4577. """
  4578. self.defaults.report_usage("on_skewy()")
  4579. obj_list = self.collection.get_selected()
  4580. xminlist = []
  4581. yminlist = []
  4582. if not obj_list:
  4583. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4584. else:
  4585. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4586. min=-360, max=360, decimals=4,
  4587. init_val=float(self.defaults['tools_transform_skew_y']))
  4588. num, ok = skewybox.get_value()
  4589. if ok:
  4590. # first get a bounding box to fit all
  4591. for obj in obj_list:
  4592. xmin, ymin, xmax, ymax = obj.bounds()
  4593. xminlist.append(xmin)
  4594. yminlist.append(ymin)
  4595. # get the minimum x,y and maximum x,y for all objects selected
  4596. xminimal = min(xminlist)
  4597. yminimal = min(yminlist)
  4598. for obj in obj_list:
  4599. obj.skew(0, num, point=(xminimal, yminimal))
  4600. obj.plot()
  4601. self.app_obj.object_changed.emit(obj)
  4602. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4603. def on_plots_updated(self):
  4604. """
  4605. Callback used to report when the plots have changed.
  4606. Adjust axes and zooms to fit.
  4607. :return: None
  4608. """
  4609. if self.is_legacy is False:
  4610. self.plotcanvas.update()
  4611. else:
  4612. self.plotcanvas.auto_adjust_axes()
  4613. self.on_zoom_fit()
  4614. self.collection.update_view()
  4615. # self.inform.emit(_("Plots updated ..."))
  4616. def on_toolbar_replot(self):
  4617. """
  4618. Callback for toolbar button. Re-plots all objects.
  4619. :return: None
  4620. """
  4621. self.defaults.report_usage("on_toolbar_replot")
  4622. self.log.debug("on_toolbar_replot()")
  4623. try:
  4624. self.collection.get_active().read_form()
  4625. except AttributeError:
  4626. self.log.debug("on_toolbar_replot(): AttributeError")
  4627. pass
  4628. self.plot_all()
  4629. def grid_status(self):
  4630. return True if self.ui.grid_snap_btn.isChecked() else False
  4631. def populate_cmenu_grids(self):
  4632. units = self.defaults['units'].lower()
  4633. # for act in self.ui.cmenu_gridmenu.actions():
  4634. # act.triggered.disconnect()
  4635. self.ui.cmenu_gridmenu.clear()
  4636. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4637. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4638. _("Grid On/Off"))
  4639. grid_toggle.setCheckable(True)
  4640. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4641. self.ui.cmenu_gridmenu.addSeparator()
  4642. for grid in sorted_list:
  4643. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4644. "%s" % str(grid))
  4645. action.triggered.connect(self.set_grid)
  4646. self.ui.cmenu_gridmenu.addSeparator()
  4647. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4648. _("Add"))
  4649. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4650. _("Delete"))
  4651. grid_add.triggered.connect(self.on_grid_add)
  4652. grid_delete.triggered.connect(self.on_grid_delete)
  4653. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4654. def set_grid(self):
  4655. menu_action = self.sender()
  4656. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4657. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4658. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4659. def on_grid_add(self):
  4660. # ## Current application units in lower Case
  4661. units = self.defaults['units'].lower()
  4662. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4663. text=_('Enter a Grid Value:'),
  4664. min=0.0000, max=99.9999, decimals=4)
  4665. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4666. val, ok = grid_add_popup.get_value()
  4667. if ok:
  4668. if float(val) == 0:
  4669. self.inform.emit('[WARNING_NOTCL] %s' %
  4670. _("Please enter a grid value with non-zero value, in Float format."))
  4671. return
  4672. else:
  4673. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4674. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4675. self.inform.emit('[success] %s...' % _("New Grid added"))
  4676. else:
  4677. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4678. else:
  4679. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4680. def on_grid_delete(self):
  4681. # ## Current application units in lower Case
  4682. units = self.defaults['units'].lower()
  4683. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4684. text='Enter a Grid Value:',
  4685. min=0.0000, max=99.9999, decimals=4)
  4686. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4687. val, ok = grid_del_popup.get_value()
  4688. if ok:
  4689. if float(val) == 0:
  4690. self.inform.emit('[WARNING_NOTCL] %s' %
  4691. _("Please enter a grid value with non-zero value, in Float format."))
  4692. return
  4693. else:
  4694. try:
  4695. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4696. except ValueError:
  4697. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4698. return
  4699. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4700. else:
  4701. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4702. def on_shortcut_list(self):
  4703. self.defaults.report_usage("on_shortcut_list()")
  4704. # add the tab if it was closed
  4705. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4706. # delete the absolute and relative position and messages in the infobar
  4707. self.ui.position_label.setText("")
  4708. # self.ui.rel_position_label.setText("")
  4709. # Switch plot_area to preferences page
  4710. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4711. # self.ui.show()
  4712. def on_select_tab(self, name):
  4713. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4714. if self.ui.splitter.sizes()[0] == 0:
  4715. self.ui.splitter.setSizes([1, 1])
  4716. else:
  4717. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4718. self.ui.splitter.setSizes([0, 1])
  4719. if name == 'project':
  4720. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4721. elif name == 'selected':
  4722. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4723. elif name == 'tool':
  4724. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4725. def on_copy_name(self):
  4726. self.defaults.report_usage("on_copy_name()")
  4727. obj = self.collection.get_active()
  4728. try:
  4729. name = obj.options["name"]
  4730. except AttributeError:
  4731. log.debug("on_copy_name() --> No object selected to copy it's name")
  4732. self.inform.emit('[WARNING_NOTCL]%s' %
  4733. _(" No object selected to copy it's name"))
  4734. return
  4735. self.clipboard.setText(name)
  4736. self.inform.emit(_("Name copied on clipboard ..."))
  4737. def on_mouse_click_over_plot(self, event):
  4738. """
  4739. Default actions are:
  4740. :param event: Contains information about the event, like which button
  4741. was clicked, the pixel coordinates and the axes coordinates.
  4742. :return: None
  4743. """
  4744. self.pos = []
  4745. if self.is_legacy is False:
  4746. event_pos = event.pos
  4747. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4748. # # Set the mouse button for panning
  4749. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4750. else:
  4751. event_pos = (event.xdata, event.ydata)
  4752. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4753. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4754. # So it can receive key presses
  4755. self.plotcanvas.native.setFocus()
  4756. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4757. if self.grid_status():
  4758. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4759. else:
  4760. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4761. try:
  4762. if event.button == 1:
  4763. # Reset here the relative coordinates so there is a new reference on the click position
  4764. if self.rel_point1 is None:
  4765. self.rel_point1 = self.pos
  4766. else:
  4767. self.rel_point2 = copy(self.rel_point1)
  4768. self.rel_point1 = self.pos
  4769. self.on_mouse_move_over_plot(event, origin_click=True)
  4770. except Exception as e:
  4771. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4772. def on_mouse_double_click_over_plot(self, event):
  4773. if event.button == 1:
  4774. self.doubleclick = True
  4775. def on_mouse_move_over_plot(self, event, origin_click=None):
  4776. """
  4777. Callback for the mouse motion event over the plot.
  4778. :param event: Contains information about the event.
  4779. :param origin_click
  4780. :return: None
  4781. """
  4782. if self.is_legacy is False:
  4783. event_pos = event.pos
  4784. if self.defaults["global_pan_button"] == '2':
  4785. pan_button = 2
  4786. else:
  4787. pan_button = 3
  4788. self.event_is_dragging = event.is_dragging
  4789. else:
  4790. event_pos = (event.xdata, event.ydata)
  4791. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4792. if self.defaults["global_pan_button"] == '2':
  4793. pan_button = 3
  4794. else:
  4795. pan_button = 2
  4796. self.event_is_dragging = self.plotcanvas.is_dragging
  4797. # So it can receive key presses but not when the Tcl Shell is active
  4798. if not self.ui.shell_dock.isVisible():
  4799. if not self.plotcanvas.native.hasFocus():
  4800. self.plotcanvas.native.setFocus()
  4801. self.pos_jump = event_pos
  4802. self.ui.popMenu.mouse_is_panning = False
  4803. if origin_click is None:
  4804. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4805. if event.button == pan_button and self.event_is_dragging == 1:
  4806. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4807. if self.ui.popMenu.popup_active:
  4808. self.ui.popMenu.popup_active = False
  4809. return
  4810. self.ui.popMenu.mouse_is_panning = True
  4811. return
  4812. if self.rel_point1 is not None:
  4813. try: # May fail in case mouse not within axes
  4814. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4815. if pos_canvas[0] is None or pos_canvas[1] is None:
  4816. return
  4817. if self.grid_status():
  4818. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4819. # Update cursor
  4820. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4821. symbol='++', edge_color=self.cursor_color_3D,
  4822. edge_width=self.defaults["global_cursor_width"],
  4823. size=self.defaults["global_cursor_size"])
  4824. else:
  4825. pos = (pos_canvas[0], pos_canvas[1])
  4826. self.dx = pos[0] - float(self.rel_point1[0])
  4827. self.dy = pos[1] - float(self.rel_point1[1])
  4828. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4829. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4830. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4831. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4832. units = self.defaults["units"].lower()
  4833. self.plotcanvas.text_hud.text = \
  4834. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4835. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4836. self.mouse = [pos[0], pos[1]]
  4837. # if the mouse is moved and the LMB is clicked then the action is a selection
  4838. if self.event_is_dragging == 1 and event.button == 1:
  4839. self.delete_selection_shape()
  4840. if self.dx < 0:
  4841. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4842. face_color=self.defaults['global_alt_sel_fill'])
  4843. self.selection_type = False
  4844. elif self.dx >= 0:
  4845. self.draw_moving_selection_shape(self.pos, pos)
  4846. self.selection_type = True
  4847. else:
  4848. self.selection_type = None
  4849. else:
  4850. self.selection_type = None
  4851. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4852. if self.defaults['global_hover']:
  4853. for obj in self.collection.get_list():
  4854. try:
  4855. # select the object(s) only if it is enabled (plotted)
  4856. if obj.options['plot']:
  4857. if obj not in self.collection.get_selected():
  4858. poly_obj = Polygon(
  4859. [(obj.options['xmin'], obj.options['ymin']),
  4860. (obj.options['xmax'], obj.options['ymin']),
  4861. (obj.options['xmax'], obj.options['ymax']),
  4862. (obj.options['xmin'], obj.options['ymax'])]
  4863. )
  4864. if Point(pos).within(poly_obj):
  4865. if obj.isHovering is False:
  4866. obj.isHovering = True
  4867. obj.notHovering = True
  4868. # create the selection box around the selected object
  4869. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4870. else:
  4871. if obj.notHovering is True:
  4872. obj.notHovering = False
  4873. obj.isHovering = False
  4874. self.delete_hover_shape()
  4875. except Exception:
  4876. # the Exception here will happen if we try to select on screen and we have an
  4877. # newly (and empty) just created Geometry or Excellon object that do not have the
  4878. # xmin, xmax, ymin, ymax options.
  4879. # In this case poly_obj creation (see above) will fail
  4880. pass
  4881. except Exception as e:
  4882. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4883. self.ui.position_label.setText("")
  4884. # self.ui.rel_position_label.setText("")
  4885. self.mouse = None
  4886. def on_mouse_click_release_over_plot(self, event):
  4887. """
  4888. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4889. and has been registered in ''self.__init__()''.
  4890. :param event: contains information about the event.
  4891. :return:
  4892. """
  4893. if self.is_legacy is False:
  4894. event_pos = event.pos
  4895. right_button = 2
  4896. else:
  4897. event_pos = (event.xdata, event.ydata)
  4898. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4899. right_button = 3
  4900. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4901. if self.grid_status():
  4902. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4903. else:
  4904. pos = (pos_canvas[0], pos_canvas[1])
  4905. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4906. # canvas menu
  4907. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4908. self.ui.popMenu.mouse_is_panning = False
  4909. self.cursor = QtGui.QCursor()
  4910. self.populate_cmenu_grids()
  4911. self.ui.popMenu.popup(self.cursor.pos())
  4912. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4913. # selection and then select a type of selection ("enclosing" or "touching")
  4914. if event.button == 1: # left click
  4915. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4916. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4917. if modifiers == QtCore.Qt.ShiftModifier:
  4918. # do not auto open the Project Tab
  4919. self.click_noproject = True
  4920. self.clipboard.setText(
  4921. self.defaults["global_point_clipboard_format"] %
  4922. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4923. )
  4924. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4925. return
  4926. if self.doubleclick is True:
  4927. self.doubleclick = False
  4928. if self.collection.get_selected():
  4929. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4930. if self.ui.splitter.sizes()[0] == 0:
  4931. self.ui.splitter.setSizes([1, 1])
  4932. try:
  4933. # delete the selection shape(S) as it may be in the way
  4934. self.delete_selection_shape()
  4935. self.delete_hover_shape()
  4936. except Exception as e:
  4937. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4938. return
  4939. else:
  4940. # WORKAROUND for LEGACY MODE
  4941. if self.is_legacy is True:
  4942. # if there is no move on canvas then we have no dragging selection
  4943. if self.dx == 0 or self.dy == 0:
  4944. self.selection_type = None
  4945. if self.selection_type is not None:
  4946. try:
  4947. self.selection_area_handler(self.pos, pos, self.selection_type)
  4948. self.selection_type = None
  4949. except Exception as e:
  4950. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4951. return
  4952. else:
  4953. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4954. if key_modifier == QtCore.Qt.ShiftModifier:
  4955. mod_key = 'Shift'
  4956. elif key_modifier == QtCore.Qt.ControlModifier:
  4957. mod_key = 'Control'
  4958. else:
  4959. mod_key = None
  4960. try:
  4961. if self.command_active is None:
  4962. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4963. # deselect, and if it's not selected then it will be selected
  4964. # If there is no active command (self.command_active is None) then we check if we clicked
  4965. # on a object by checking the bounding limits against mouse click position
  4966. if mod_key == self.defaults["global_mselect_key"]:
  4967. self.select_objects(key='multisel')
  4968. else:
  4969. # If there is no active command (self.command_active is None) then we check if
  4970. # we clicked on a object by checking the bounding limits against mouse click position
  4971. self.select_objects()
  4972. self.delete_hover_shape()
  4973. except Exception as e:
  4974. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4975. return
  4976. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4977. """
  4978. :param start_pos: mouse position when the selection LMB click was done
  4979. :param end_pos: mouse position when the left mouse button is released
  4980. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4981. :return:
  4982. """
  4983. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4984. # delete previous selection shape
  4985. self.delete_selection_shape()
  4986. # make all objects inactive
  4987. self.collection.set_all_inactive()
  4988. for obj in self.collection.get_list():
  4989. try:
  4990. # select the object(s) only if it is enabled (plotted)
  4991. if obj.options['plot']:
  4992. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4993. (obj.options['xmax'], obj.options['ymin']),
  4994. (obj.options['xmax'], obj.options['ymax']),
  4995. (obj.options['xmin'], obj.options['ymax'])])
  4996. if sel_type is True:
  4997. if poly_obj.within(poly_selection):
  4998. # create the selection box around the selected object
  4999. if self.defaults['global_selection_shape'] is True:
  5000. self.draw_selection_shape(obj)
  5001. self.collection.set_active(obj.options['name'])
  5002. else:
  5003. if poly_selection.intersects(poly_obj):
  5004. # create the selection box around the selected object
  5005. if self.defaults['global_selection_shape'] is True:
  5006. self.draw_selection_shape(obj)
  5007. self.collection.set_active(obj.options['name'])
  5008. obj.selection_shape_drawn = True
  5009. except Exception as e:
  5010. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5011. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5012. # In this case poly_obj creation (see above) will fail
  5013. log.debug("App.selection_area_handler() --> %s" % str(e))
  5014. def select_objects(self, key=None):
  5015. """
  5016. Will select objects clicked on canvas
  5017. :param key: for future use in cumulative selection
  5018. :return:
  5019. """
  5020. # list where we store the overlapped objects under our mouse left click position
  5021. if key is None:
  5022. self.objects_under_the_click_list = []
  5023. # Populate the list with the overlapped objects on the click position
  5024. curr_x, curr_y = self.pos
  5025. for obj in self.all_objects_list:
  5026. # ScriptObject and DocumentObject objects can't be selected
  5027. if obj.kind == 'script' or obj.kind == 'document':
  5028. continue
  5029. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5030. continue
  5031. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5032. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5033. if obj.options['name'] not in self.objects_under_the_click_list:
  5034. if obj.options['plot']:
  5035. # add objects to the objects_under_the_click list only if the object is plotted
  5036. # (active and not disabled)
  5037. self.objects_under_the_click_list.append(obj.options['name'])
  5038. try:
  5039. if self.objects_under_the_click_list:
  5040. curr_sel_obj = self.collection.get_active()
  5041. # case when there is only an object under the click and we toggle it
  5042. if len(self.objects_under_the_click_list) == 1:
  5043. if curr_sel_obj is None:
  5044. self.collection.set_active(self.objects_under_the_click_list[0])
  5045. curr_sel_obj = self.collection.get_active()
  5046. # create the selection box around the selected object
  5047. if self.defaults['global_selection_shape'] is True:
  5048. self.draw_selection_shape(curr_sel_obj)
  5049. curr_sel_obj.selection_shape_drawn = True
  5050. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5051. self.collection.on_objects_selection(False)
  5052. self.delete_selection_shape()
  5053. curr_sel_obj.selection_shape_drawn = False
  5054. self.collection.set_active(self.objects_under_the_click_list[0])
  5055. curr_sel_obj = self.collection.get_active()
  5056. # create the selection box around the selected object
  5057. if self.defaults['global_selection_shape'] is True:
  5058. self.draw_selection_shape(curr_sel_obj)
  5059. curr_sel_obj.selection_shape_drawn = True
  5060. self.selected_message(curr_sel_obj=curr_sel_obj)
  5061. elif curr_sel_obj.selection_shape_drawn is False:
  5062. if self.defaults['global_selection_shape'] is True:
  5063. self.draw_selection_shape(curr_sel_obj)
  5064. curr_sel_obj.selection_shape_drawn = True
  5065. else:
  5066. self.collection.on_objects_selection(False)
  5067. self.delete_selection_shape()
  5068. if self.call_source != 'app':
  5069. self.call_source = 'app'
  5070. self.selected_message(curr_sel_obj=curr_sel_obj)
  5071. else:
  5072. # If there is no selected object
  5073. # make active the first element of the overlapped objects list
  5074. if self.collection.get_active() is None:
  5075. self.collection.set_active(self.objects_under_the_click_list[0])
  5076. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5077. name_sel_obj = self.collection.get_active().options['name']
  5078. # In case that there is a selected object but it is not in the overlapped object list
  5079. # make that object inactive and activate the first element in the overlapped object list
  5080. if name_sel_obj not in self.objects_under_the_click_list:
  5081. self.collection.set_inactive(name_sel_obj)
  5082. name_sel_obj = self.objects_under_the_click_list[0]
  5083. self.collection.set_active(name_sel_obj)
  5084. else:
  5085. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5086. self.collection.set_all_inactive()
  5087. self.collection.set_active(
  5088. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5089. curr_sel_obj = self.collection.get_active()
  5090. # delete the possible selection box around a possible selected object
  5091. self.delete_selection_shape()
  5092. curr_sel_obj.selection_shape_drawn = False
  5093. # create the selection box around the selected object
  5094. if self.defaults['global_selection_shape'] is True:
  5095. self.draw_selection_shape(curr_sel_obj)
  5096. curr_sel_obj.selection_shape_drawn = True
  5097. self.selected_message(curr_sel_obj=curr_sel_obj)
  5098. else:
  5099. # deselect everything
  5100. self.collection.on_objects_selection(False)
  5101. # delete the possible selection box around a possible selected object
  5102. self.delete_selection_shape()
  5103. for o in self.collection.get_list():
  5104. o.selection_shape_drawn = False
  5105. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5106. # only when working on App
  5107. if self.call_source == 'app':
  5108. if self.click_noproject is False:
  5109. # if the Tool Tab is in focus don't change focus to Project Tab
  5110. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5111. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5112. else:
  5113. # restore auto open the Project Tab
  5114. self.click_noproject = False
  5115. # delete any text in the status bar, implicitly the last object name that was selected
  5116. # self.inform.emit("")
  5117. else:
  5118. self.call_source = 'app'
  5119. except Exception as e:
  5120. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5121. def selected_message(self, curr_sel_obj):
  5122. if curr_sel_obj:
  5123. if curr_sel_obj.kind == 'gerber':
  5124. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5125. color='green',
  5126. name=str(curr_sel_obj.options['name']),
  5127. tx=_("selected"))
  5128. )
  5129. elif curr_sel_obj.kind == 'excellon':
  5130. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5131. color='brown',
  5132. name=str(curr_sel_obj.options['name']),
  5133. tx=_("selected"))
  5134. )
  5135. elif curr_sel_obj.kind == 'cncjob':
  5136. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5137. color='blue',
  5138. name=str(curr_sel_obj.options['name']),
  5139. tx=_("selected"))
  5140. )
  5141. elif curr_sel_obj.kind == 'geometry':
  5142. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5143. color='red',
  5144. name=str(curr_sel_obj.options['name']),
  5145. tx=_("selected"))
  5146. )
  5147. def delete_hover_shape(self):
  5148. self.hover_shapes.clear()
  5149. self.hover_shapes.redraw()
  5150. def draw_hover_shape(self, sel_obj, color=None):
  5151. """
  5152. :param sel_obj: The object for which the hover shape must be drawn
  5153. :param color: The color of the hover shape
  5154. :return: None
  5155. """
  5156. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5157. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5158. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5159. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5160. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5161. if self.defaults['units'].upper() == 'MM':
  5162. hover_rect = hover_rect.buffer(-0.1)
  5163. hover_rect = hover_rect.buffer(0.2)
  5164. else:
  5165. hover_rect = hover_rect.buffer(-0.00393)
  5166. hover_rect = hover_rect.buffer(0.00787)
  5167. # if color:
  5168. # face = Color(color)
  5169. # face.alpha = 0.2
  5170. # outline = Color(color, alpha=0.8)
  5171. # else:
  5172. # face = Color(self.defaults['global_sel_fill'])
  5173. # face.alpha = 0.2
  5174. # outline = self.defaults['global_sel_line']
  5175. if color:
  5176. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5177. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5178. else:
  5179. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5180. outline = self.defaults['global_sel_line']
  5181. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5182. if self.is_legacy is True:
  5183. self.hover_shapes.redraw()
  5184. def delete_selection_shape(self):
  5185. self.move_tool.sel_shapes.clear()
  5186. self.move_tool.sel_shapes.redraw()
  5187. def draw_selection_shape(self, sel_obj, color=None):
  5188. """
  5189. Will draw a selection shape around the selected object.
  5190. :param sel_obj: The object for which the selection shape must be drawn
  5191. :param color: The color for the selection shape.
  5192. :return: None
  5193. """
  5194. if sel_obj is None:
  5195. return
  5196. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5197. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5198. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5199. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5200. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5201. if self.defaults['units'].upper() == 'MM':
  5202. sel_rect = sel_rect.buffer(-0.1)
  5203. sel_rect = sel_rect.buffer(0.2)
  5204. else:
  5205. sel_rect = sel_rect.buffer(-0.00393)
  5206. sel_rect = sel_rect.buffer(0.00787)
  5207. if color:
  5208. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5209. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5210. else:
  5211. if self.is_legacy is False:
  5212. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5213. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5214. else:
  5215. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5216. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5217. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5218. color=outline,
  5219. face_color=face,
  5220. update=True,
  5221. layer=0,
  5222. tolerance=None))
  5223. if self.is_legacy is True:
  5224. self.move_tool.sel_shapes.redraw()
  5225. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5226. """
  5227. Will draw a selection shape when dragging mouse on canvas.
  5228. :param old_coords: Old coordinates
  5229. :param coords: New coordinates
  5230. :param kwargs: Keyword arguments
  5231. :return:
  5232. """
  5233. if 'color' in kwargs:
  5234. color = kwargs['color']
  5235. else:
  5236. color = self.defaults['global_sel_line']
  5237. if 'face_color' in kwargs:
  5238. face_color = kwargs['face_color']
  5239. else:
  5240. face_color = self.defaults['global_sel_fill']
  5241. if 'face_alpha' in kwargs:
  5242. face_alpha = kwargs['face_alpha']
  5243. else:
  5244. face_alpha = 0.3
  5245. x0, y0 = old_coords
  5246. x1, y1 = coords
  5247. pt1 = (x0, y0)
  5248. pt2 = (x1, y0)
  5249. pt3 = (x1, y1)
  5250. pt4 = (x0, y1)
  5251. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5252. # color_t = Color(face_color)
  5253. # color_t.alpha = face_alpha
  5254. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5255. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5256. layer=0, tolerance=None)
  5257. if self.is_legacy is True:
  5258. self.move_tool.sel_shapes.redraw()
  5259. def on_file_new_click(self):
  5260. """
  5261. Callback for menu item File -> New.
  5262. Executed on clicking the Menu -> File -> New Project
  5263. :return:
  5264. """
  5265. if self.collection.get_list() and self.should_we_save:
  5266. msgbox = QtWidgets.QMessageBox()
  5267. # msgbox.setText("<B>Save changes ...</B>")
  5268. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5269. "Creating a New project will delete them.\n"
  5270. "Do you want to Save the project?"))
  5271. msgbox.setWindowTitle(_("Save changes"))
  5272. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5273. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5274. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5275. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5276. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5277. msgbox.setDefaultButton(bt_yes)
  5278. msgbox.exec_()
  5279. response = msgbox.clickedButton()
  5280. if response == bt_yes:
  5281. self.on_file_saveprojectas()
  5282. elif response == bt_cancel:
  5283. return
  5284. elif response == bt_no:
  5285. self.on_file_new()
  5286. else:
  5287. self.on_file_new()
  5288. self.inform.emit('[success] %s...' % _("New Project created"))
  5289. def on_file_new(self, cli=None):
  5290. """
  5291. Returns the application to its startup state. This method is thread-safe.
  5292. :param cli: Boolean. If True this method was run from command line
  5293. :return: None
  5294. """
  5295. self.defaults.report_usage("on_file_new")
  5296. # Remove everything from memory
  5297. App.log.debug("on_file_new()")
  5298. # close any editor that might be open
  5299. if self.call_source != 'app':
  5300. self.editor2object(cleanup=True)
  5301. # ## EDITOR section
  5302. self.geo_editor = FlatCAMGeoEditor(self)
  5303. self.exc_editor = FlatCAMExcEditor(self)
  5304. self.grb_editor = FlatCAMGrbEditor(self)
  5305. # Clear pool
  5306. self.clear_pool()
  5307. for obj in self.collection.get_list():
  5308. # delete shapes left drawn from mark shape_collections, if any
  5309. if isinstance(obj, GerberObject):
  5310. try:
  5311. for el in obj.mark_shapes:
  5312. obj.mark_shapes[el].clear(update=True)
  5313. obj.mark_shapes[el].enabled = False
  5314. del el
  5315. except AttributeError:
  5316. pass
  5317. # also delete annotation shapes, if any
  5318. elif isinstance(obj, CNCJobObject):
  5319. try:
  5320. obj.text_col.enabled = False
  5321. del obj.text_col
  5322. obj.annotation.clear(update=True)
  5323. del obj.annotation
  5324. except AttributeError:
  5325. pass
  5326. # delete the exclusion areas
  5327. self.exc_areas.clear_shapes()
  5328. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5329. self.shell.init_tcl()
  5330. # delete any selection shape on canvas
  5331. self.delete_selection_shape()
  5332. # delete all FlatCAM objects
  5333. self.collection.delete_all()
  5334. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5335. self.setup_component_editor()
  5336. # Clear project filename
  5337. self.project_filename = None
  5338. # Load the application defaults
  5339. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5340. # Re-fresh project options
  5341. self.on_options_app2project()
  5342. # Init FlatCAMTools
  5343. self.init_tools()
  5344. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5345. if cli is None:
  5346. # we need to go in reverse because once we remove a tab then the index changes
  5347. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5348. # and so on. Therefore the deletion should be done in reverse
  5349. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5350. for index in range(wdg_count, -1, -1):
  5351. try:
  5352. self.ui.plot_tab_area.closeTab(index)
  5353. except Exception as e:
  5354. log.debug("App.on_file_new() --> %s" % str(e))
  5355. # # And then add again the Plot Area
  5356. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5357. self.ui.plot_tab_area.protectTab(0)
  5358. # take the focus of the Notebook on Project Tab.
  5359. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5360. self.set_ui_title(name=_("New Project - Not saved"))
  5361. def obj_properties(self):
  5362. """
  5363. Will launch the object Properties Tool
  5364. :return:
  5365. """
  5366. self.defaults.report_usage("obj_properties()")
  5367. self.properties_tool.run(toggle=False)
  5368. def on_project_context_save(self):
  5369. """
  5370. Wrapper, will save the object function of it's type
  5371. :return:
  5372. """
  5373. obj = self.collection.get_active()
  5374. if type(obj) == GeometryObject:
  5375. self.on_file_exportdxf()
  5376. elif type(obj) == ExcellonObject:
  5377. self.on_file_saveexcellon()
  5378. elif type(obj) == CNCJobObject:
  5379. obj.on_exportgcode_button_click()
  5380. elif type(obj) == GerberObject:
  5381. self.on_file_savegerber()
  5382. elif type(obj) == ScriptObject:
  5383. self.on_file_savescript()
  5384. elif type(obj) == DocumentObject:
  5385. self.on_file_savedocument()
  5386. def obj_move(self):
  5387. """
  5388. Callback for the Move menu entry in various Context Menu's.
  5389. :return:
  5390. """
  5391. self.defaults.report_usage("obj_move()")
  5392. self.move_tool.run(toggle=False)
  5393. def on_fileopengerber(self, signal, name=None):
  5394. """
  5395. File menu callback for opening a Gerber.
  5396. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5397. :param name:
  5398. :return: None
  5399. """
  5400. self.defaults.report_usage("on_fileopengerber")
  5401. App.log.debug("on_fileopengerber()")
  5402. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5403. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5404. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5405. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5406. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5407. "*.mil);;" \
  5408. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5409. "Allegro Files (*.art);;" \
  5410. "Mentor Files (*.pho *.gdo);;" \
  5411. "All Files (*.*)"
  5412. if name is None:
  5413. try:
  5414. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5415. directory=self.get_last_folder(),
  5416. filter=_filter_)
  5417. except TypeError:
  5418. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5419. filenames = [str(filename) for filename in filenames]
  5420. else:
  5421. filenames = [name]
  5422. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5423. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5424. _("Opening Gerber file.")),
  5425. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5426. color=QtGui.QColor("gray"))
  5427. if len(filenames) == 0:
  5428. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5429. else:
  5430. for filename in filenames:
  5431. if filename != '':
  5432. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5433. def on_fileopenexcellon(self, signal, name=None):
  5434. """
  5435. File menu callback for opening an Excellon file.
  5436. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5437. :param name:
  5438. :return: None
  5439. """
  5440. self.defaults.report_usage("on_fileopenexcellon")
  5441. App.log.debug("on_fileopenexcellon()")
  5442. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5443. "All Files (*.*)"
  5444. if name is None:
  5445. try:
  5446. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5447. directory=self.get_last_folder(),
  5448. filter=_filter_)
  5449. except TypeError:
  5450. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5451. filenames = [str(filename) for filename in filenames]
  5452. else:
  5453. filenames = [str(name)]
  5454. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5455. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5456. _("Opening Excellon file.")),
  5457. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5458. color=QtGui.QColor("gray"))
  5459. if len(filenames) == 0:
  5460. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5461. else:
  5462. for filename in filenames:
  5463. if filename != '':
  5464. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5465. def on_fileopengcode(self, signal, name=None):
  5466. """
  5467. File menu call back for opening gcode.
  5468. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5469. :param name:
  5470. :return:
  5471. """
  5472. self.defaults.report_usage("on_fileopengcode")
  5473. App.log.debug("on_fileopengcode()")
  5474. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5475. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5476. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5477. "All Files (*.*)"
  5478. if name is None:
  5479. try:
  5480. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5481. directory=self.get_last_folder(),
  5482. filter=_filter_)
  5483. except TypeError:
  5484. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5485. filenames = [str(filename) for filename in filenames]
  5486. else:
  5487. filenames = [name]
  5488. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5489. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5490. _("Opening G-Code file.")),
  5491. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5492. color=QtGui.QColor("gray"))
  5493. if len(filenames) == 0:
  5494. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5495. else:
  5496. for filename in filenames:
  5497. if filename != '':
  5498. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5499. def on_file_openproject(self, signal):
  5500. """
  5501. File menu callback for opening a project.
  5502. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5503. :return: None
  5504. """
  5505. self.defaults.report_usage("on_file_openproject")
  5506. App.log.debug("on_file_openproject()")
  5507. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5508. try:
  5509. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5510. directory=self.get_last_folder(), filter=_filter_)
  5511. except TypeError:
  5512. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5513. # The Qt methods above will return a QString which can cause problems later.
  5514. # So far json.dump() will fail to serialize it.
  5515. # TODO: Improve the serialization methods and remove this fix.
  5516. filename = str(filename)
  5517. if filename == "":
  5518. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5519. else:
  5520. # self.worker_task.emit({'fcn': self.open_project,
  5521. # 'params': [filename]})
  5522. # The above was failing because open_project() is not
  5523. # thread safe. The new_project()
  5524. self.open_project(filename)
  5525. def on_fileopenhpgl2(self, signal, name=None):
  5526. """
  5527. File menu callback for opening a HPGL2.
  5528. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5529. :param name:
  5530. :return: None
  5531. """
  5532. self.defaults.report_usage("on_fileopenhpgl2")
  5533. App.log.debug("on_fileopenhpgl2()")
  5534. _filter_ = "HPGL2 Files (*.plt);;" \
  5535. "All Files (*.*)"
  5536. if name is None:
  5537. try:
  5538. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5539. directory=self.get_last_folder(),
  5540. filter=_filter_)
  5541. except TypeError:
  5542. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5543. filenames = [str(filename) for filename in filenames]
  5544. else:
  5545. filenames = [name]
  5546. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5547. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5548. _("Opening HPGL2 file.")),
  5549. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5550. color=QtGui.QColor("gray"))
  5551. if len(filenames) == 0:
  5552. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5553. else:
  5554. for filename in filenames:
  5555. if filename != '':
  5556. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5557. def on_file_openconfig(self, signal):
  5558. """
  5559. File menu callback for opening a config file.
  5560. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5561. :return: None
  5562. """
  5563. self.defaults.report_usage("on_file_openconfig")
  5564. App.log.debug("on_file_openconfig()")
  5565. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5566. try:
  5567. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5568. directory=self.data_path, filter=_filter_)
  5569. except TypeError:
  5570. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5571. filter=_filter_)
  5572. if filename == "":
  5573. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5574. else:
  5575. self.open_config_file(filename)
  5576. def on_file_exportsvg(self):
  5577. """
  5578. Callback for menu item File->Export SVG.
  5579. :return: None
  5580. """
  5581. self.defaults.report_usage("on_file_exportsvg")
  5582. App.log.debug("on_file_exportsvg()")
  5583. obj = self.collection.get_active()
  5584. if obj is None:
  5585. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5586. msg = _("Please Select a Geometry object to export")
  5587. msgbox = QtWidgets.QMessageBox()
  5588. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5589. msgbox.setInformativeText(msg)
  5590. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5591. msgbox.setDefaultButton(bt_ok)
  5592. msgbox.exec_()
  5593. return
  5594. # Check for more compatible types and add as required
  5595. if (not isinstance(obj, GeometryObject)
  5596. and not isinstance(obj, GerberObject)
  5597. and not isinstance(obj, CNCJobObject)
  5598. and not isinstance(obj, ExcellonObject)):
  5599. msg = '[ERROR_NOTCL] %s' % \
  5600. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5601. msgbox = QtWidgets.QMessageBox()
  5602. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5603. msgbox.setInformativeText(msg)
  5604. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5605. msgbox.setDefaultButton(bt_ok)
  5606. msgbox.exec_()
  5607. return
  5608. name = obj.options["name"]
  5609. _filter = "SVG File (*.svg);;All Files (*.*)"
  5610. try:
  5611. filename, _f = FCFileSaveDialog.get_saved_filename(
  5612. caption=_("Export SVG"),
  5613. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5614. filter=_filter)
  5615. except TypeError:
  5616. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5617. filename = str(filename)
  5618. if filename == "":
  5619. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5620. return
  5621. else:
  5622. self.export_svg(name, filename)
  5623. if self.defaults["global_open_style"] is False:
  5624. self.file_opened.emit("SVG", filename)
  5625. self.file_saved.emit("SVG", filename)
  5626. def on_file_exportpng(self):
  5627. self.defaults.report_usage("on_file_exportpng")
  5628. App.log.debug("on_file_exportpng()")
  5629. self.date = str(datetime.today()).rpartition('.')[0]
  5630. self.date = ''.join(c for c in self.date if c not in ':-')
  5631. self.date = self.date.replace(' ', '_')
  5632. if self.is_legacy is False:
  5633. image = _screenshot()
  5634. data = np.asarray(image)
  5635. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5636. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5637. return
  5638. filter_ = "PNG File (*.png);;All Files (*.*)"
  5639. try:
  5640. filename, _f = FCFileSaveDialog.get_saved_filename(
  5641. caption=_("Export PNG Image"),
  5642. directory=self.get_last_save_folder() + '/png_' + self.date,
  5643. filter=filter_)
  5644. except TypeError:
  5645. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5646. filename = str(filename)
  5647. if filename == "":
  5648. self.inform.emit(_("Cancelled."))
  5649. return
  5650. else:
  5651. if self.is_legacy is False:
  5652. write_png(filename, data)
  5653. else:
  5654. self.plotcanvas.figure.savefig(filename)
  5655. if self.defaults["global_open_style"] is False:
  5656. self.file_opened.emit("png", filename)
  5657. self.file_saved.emit("png", filename)
  5658. def on_file_savegerber(self):
  5659. """
  5660. Callback for menu item in Project context menu.
  5661. :return: None
  5662. """
  5663. self.defaults.report_usage("on_file_savegerber")
  5664. App.log.debug("on_file_savegerber()")
  5665. obj = self.collection.get_active()
  5666. if obj is None:
  5667. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5668. return
  5669. # Check for more compatible types and add as required
  5670. if not isinstance(obj, GerberObject):
  5671. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5672. return
  5673. name = self.collection.get_active().options["name"]
  5674. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5675. try:
  5676. filename, _f = FCFileSaveDialog.get_saved_filename(
  5677. caption="Save Gerber source file",
  5678. directory=self.get_last_save_folder() + '/' + name,
  5679. filter=_filter)
  5680. except TypeError:
  5681. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5682. filename = str(filename)
  5683. if filename == "":
  5684. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5685. return
  5686. else:
  5687. self.save_source_file(name, filename)
  5688. if self.defaults["global_open_style"] is False:
  5689. self.file_opened.emit("Gerber", filename)
  5690. self.file_saved.emit("Gerber", filename)
  5691. def on_file_savescript(self):
  5692. """
  5693. Callback for menu item in Project context menu.
  5694. :return: None
  5695. """
  5696. self.defaults.report_usage("on_file_savescript")
  5697. App.log.debug("on_file_savescript()")
  5698. obj = self.collection.get_active()
  5699. if obj is None:
  5700. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5701. return
  5702. # Check for more compatible types and add as required
  5703. if not isinstance(obj, ScriptObject):
  5704. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5705. return
  5706. name = self.collection.get_active().options["name"]
  5707. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5708. try:
  5709. filename, _f = FCFileSaveDialog.get_saved_filename(
  5710. caption="Save Script source file",
  5711. directory=self.get_last_save_folder() + '/' + name,
  5712. filter=_filter)
  5713. except TypeError:
  5714. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5715. filename = str(filename)
  5716. if filename == "":
  5717. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5718. return
  5719. else:
  5720. self.save_source_file(name, filename)
  5721. if self.defaults["global_open_style"] is False:
  5722. self.file_opened.emit("Script", filename)
  5723. self.file_saved.emit("Script", filename)
  5724. def on_file_savedocument(self):
  5725. """
  5726. Callback for menu item in Project context menu.
  5727. :return: None
  5728. """
  5729. self.defaults.report_usage("on_file_savedocument")
  5730. App.log.debug("on_file_savedocument()")
  5731. obj = self.collection.get_active()
  5732. if obj is None:
  5733. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5734. return
  5735. # Check for more compatible types and add as required
  5736. if not isinstance(obj, ScriptObject):
  5737. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5738. return
  5739. name = self.collection.get_active().options["name"]
  5740. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5741. try:
  5742. filename, _f = FCFileSaveDialog.get_saved_filename(
  5743. caption="Save Document source file",
  5744. directory=self.get_last_save_folder() + '/' + name,
  5745. filter=_filter)
  5746. except TypeError:
  5747. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5748. filename = str(filename)
  5749. if filename == "":
  5750. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5751. return
  5752. else:
  5753. self.save_source_file(name, filename)
  5754. if self.defaults["global_open_style"] is False:
  5755. self.file_opened.emit("Document", filename)
  5756. self.file_saved.emit("Document", filename)
  5757. def on_file_saveexcellon(self):
  5758. """
  5759. Callback for menu item in project context menu.
  5760. :return: None
  5761. """
  5762. self.defaults.report_usage("on_file_saveexcellon")
  5763. App.log.debug("on_file_saveexcellon()")
  5764. obj = self.collection.get_active()
  5765. if obj is None:
  5766. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5767. return
  5768. # Check for more compatible types and add as required
  5769. if not isinstance(obj, ExcellonObject):
  5770. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5771. return
  5772. name = self.collection.get_active().options["name"]
  5773. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5774. try:
  5775. filename, _f = FCFileSaveDialog.get_saved_filename(
  5776. caption=_("Save Excellon source file"),
  5777. directory=self.get_last_save_folder() + '/' + name,
  5778. filter=_filter)
  5779. except TypeError:
  5780. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5781. filename = str(filename)
  5782. if filename == "":
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5784. return
  5785. else:
  5786. self.save_source_file(name, filename)
  5787. if self.defaults["global_open_style"] is False:
  5788. self.file_opened.emit("Excellon", filename)
  5789. self.file_saved.emit("Excellon", filename)
  5790. def on_file_exportexcellon(self):
  5791. """
  5792. Callback for menu item File->Export->Excellon.
  5793. :return: None
  5794. """
  5795. self.defaults.report_usage("on_file_exportexcellon")
  5796. App.log.debug("on_file_exportexcellon()")
  5797. obj = self.collection.get_active()
  5798. if obj is None:
  5799. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5800. return
  5801. # Check for more compatible types and add as required
  5802. if not isinstance(obj, ExcellonObject):
  5803. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5804. return
  5805. name = self.collection.get_active().options["name"]
  5806. _filter = self.defaults["excellon_save_filters"]
  5807. try:
  5808. filename, _f = FCFileSaveDialog.get_saved_filename(
  5809. caption=_("Export Excellon"),
  5810. directory=self.get_last_save_folder() + '/' + name,
  5811. filter=_filter)
  5812. except TypeError:
  5813. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5814. filename = str(filename)
  5815. if filename == "":
  5816. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5817. return
  5818. else:
  5819. used_extension = filename.rpartition('.')[2]
  5820. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5821. self.export_excellon(name, filename)
  5822. if self.defaults["global_open_style"] is False:
  5823. self.file_opened.emit("Excellon", filename)
  5824. self.file_saved.emit("Excellon", filename)
  5825. def on_file_exportgerber(self):
  5826. """
  5827. Callback for menu item File->Export->Gerber.
  5828. :return: None
  5829. """
  5830. self.defaults.report_usage("on_file_exportgerber")
  5831. App.log.debug("on_file_exportgerber()")
  5832. obj = self.collection.get_active()
  5833. if obj is None:
  5834. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5835. return
  5836. # Check for more compatible types and add as required
  5837. if not isinstance(obj, GerberObject):
  5838. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5839. return
  5840. name = self.collection.get_active().options["name"]
  5841. _filter_ = self.defaults['gerber_save_filters']
  5842. try:
  5843. filename, _f = FCFileSaveDialog.get_saved_filename(
  5844. caption=_("Export Gerber"),
  5845. directory=self.get_last_save_folder() + '/' + name,
  5846. filter=_filter_)
  5847. except TypeError:
  5848. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5849. filename = str(filename)
  5850. if filename == "":
  5851. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5852. return
  5853. else:
  5854. used_extension = filename.rpartition('.')[2]
  5855. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5856. self.export_gerber(name, filename)
  5857. if self.defaults["global_open_style"] is False:
  5858. self.file_opened.emit("Gerber", filename)
  5859. self.file_saved.emit("Gerber", filename)
  5860. def on_file_exportdxf(self):
  5861. """
  5862. Callback for menu item File->Export DXF.
  5863. :return: None
  5864. """
  5865. self.defaults.report_usage("on_file_exportdxf")
  5866. App.log.debug("on_file_exportdxf()")
  5867. obj = self.collection.get_active()
  5868. if obj is None:
  5869. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5870. msg = _("Please Select a Geometry object to export")
  5871. msgbox = QtWidgets.QMessageBox()
  5872. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5873. msgbox.setInformativeText(msg)
  5874. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5875. msgbox.setDefaultButton(bt_ok)
  5876. msgbox.exec_()
  5877. return
  5878. # Check for more compatible types and add as required
  5879. if not isinstance(obj, GeometryObject):
  5880. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5881. msgbox = QtWidgets.QMessageBox()
  5882. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5883. msgbox.setInformativeText(msg)
  5884. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5885. msgbox.setDefaultButton(bt_ok)
  5886. msgbox.exec_()
  5887. return
  5888. name = self.collection.get_active().options["name"]
  5889. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5890. try:
  5891. filename, _f = FCFileSaveDialog.get_saved_filename(
  5892. caption=_("Export DXF"),
  5893. directory=self.get_last_save_folder() + '/' + name,
  5894. filter=_filter_)
  5895. except TypeError:
  5896. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5897. filename = str(filename)
  5898. if filename == "":
  5899. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5900. return
  5901. else:
  5902. self.export_dxf(name, filename)
  5903. if self.defaults["global_open_style"] is False:
  5904. self.file_opened.emit("DXF", filename)
  5905. self.file_saved.emit("DXF", filename)
  5906. def on_file_importsvg(self, type_of_obj):
  5907. """
  5908. Callback for menu item File->Import SVG.
  5909. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5910. :type type_of_obj: str
  5911. :return: None
  5912. """
  5913. self.defaults.report_usage("on_file_importsvg")
  5914. App.log.debug("on_file_importsvg()")
  5915. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5916. try:
  5917. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5918. directory=self.get_last_folder(), filter=_filter_)
  5919. except TypeError:
  5920. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5921. filter=_filter_)
  5922. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5923. type_of_obj = "geometry"
  5924. filenames = [str(filename) for filename in filenames]
  5925. if len(filenames) == 0:
  5926. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5927. else:
  5928. for filename in filenames:
  5929. if filename != '':
  5930. self.worker_task.emit({'fcn': self.import_svg,
  5931. 'params': [filename, type_of_obj]})
  5932. def on_file_importdxf(self, type_of_obj):
  5933. """
  5934. Callback for menu item File->Import DXF.
  5935. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5936. :type type_of_obj: str
  5937. :return: None
  5938. """
  5939. self.defaults.report_usage("on_file_importdxf")
  5940. App.log.debug("on_file_importdxf()")
  5941. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5942. try:
  5943. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5944. directory=self.get_last_folder(),
  5945. filter=_filter_)
  5946. except TypeError:
  5947. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5948. filter=_filter_)
  5949. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5950. type_of_obj = "geometry"
  5951. filenames = [str(filename) for filename in filenames]
  5952. if len(filenames) == 0:
  5953. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5954. else:
  5955. for filename in filenames:
  5956. if filename != '':
  5957. self.worker_task.emit({'fcn': self.import_dxf,
  5958. 'params': [filename, type_of_obj]})
  5959. # ###############################################################################################################
  5960. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5961. # ###############################################################################################################
  5962. def init_code_editor(self, name):
  5963. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5964. # add the tab if it was closed
  5965. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5966. self.text_editor_tab.setObjectName('text_editor_tab')
  5967. # delete the absolute and relative position and messages in the infobar
  5968. self.ui.position_label.setText("")
  5969. # self.ui.rel_position_label.setText("")
  5970. # first clear previous text in text editor (if any)
  5971. self.text_editor_tab.code_editor.clear()
  5972. self.text_editor_tab.code_editor.setReadOnly(False)
  5973. self.toggle_codeeditor = True
  5974. self.text_editor_tab.code_editor.completer_enable = False
  5975. self.text_editor_tab.buttonRun.hide()
  5976. # make sure to keep a reference to the code editor
  5977. self.reference_code_editor = self.text_editor_tab.code_editor
  5978. # Switch plot_area to CNCJob tab
  5979. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5980. def on_view_source(self):
  5981. """
  5982. Called when the user wants to see the source file of the selected object
  5983. :return:
  5984. """
  5985. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5986. self.proc_container.view.set_busy(_("Loading..."))
  5987. try:
  5988. obj = self.collection.get_active()
  5989. except Exception as e:
  5990. log.debug("App.on_view_source() --> %s" % str(e))
  5991. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5992. return 'fail'
  5993. if obj is None:
  5994. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5995. return 'fail'
  5996. flt = "All Files (*.*)"
  5997. if obj.kind == 'gerber':
  5998. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5999. elif obj.kind == 'excellon':
  6000. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6001. elif obj.kind == 'cncjob':
  6002. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6003. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6004. # add the tab if it was closed
  6005. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6006. self.source_editor_tab.setObjectName('source_editor_tab')
  6007. # delete the absolute and relative position and messages in the infobar
  6008. self.ui.position_label.setText("")
  6009. # self.ui.rel_position_label.setText("")
  6010. # first clear previous text in text editor (if any)
  6011. self.source_editor_tab.code_editor.clear()
  6012. self.source_editor_tab.code_editor.setReadOnly(False)
  6013. self.source_editor_tab.code_editor.completer_enable = False
  6014. self.source_editor_tab.buttonRun.hide()
  6015. # Switch plot_area to CNCJob tab
  6016. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6017. try:
  6018. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6019. except TypeError:
  6020. pass
  6021. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6022. try:
  6023. self.source_editor_tab.buttonSave.clicked.disconnect()
  6024. except TypeError:
  6025. pass
  6026. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6027. # then append the text from GCode to the text editor
  6028. if obj.kind == 'cncjob':
  6029. try:
  6030. file = obj.export_gcode(
  6031. preamble=self.defaults["cncjob_prepend"],
  6032. postamble=self.defaults["cncjob_append"],
  6033. to_file=True)
  6034. if file == 'fail':
  6035. return 'fail'
  6036. except AttributeError:
  6037. self.inform.emit('[WARNING_NOTCL] %s' %
  6038. _("There is no selected object for which to see it's source file code."))
  6039. return 'fail'
  6040. else:
  6041. try:
  6042. file = StringIO(obj.source_file)
  6043. except (AttributeError, TypeError):
  6044. self.inform.emit('[WARNING_NOTCL] %s' %
  6045. _("There is no selected object for which to see it's source file code."))
  6046. return 'fail'
  6047. self.source_editor_tab.t_frame.hide()
  6048. try:
  6049. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6050. # for line in file:
  6051. # QtWidgets.QApplication.processEvents()
  6052. # proc_line = str(line).strip('\n')
  6053. # self.source_editor_tab.code_editor.append(proc_line)
  6054. except Exception as e:
  6055. log.debug('App.on_view_source() -->%s' % str(e))
  6056. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6057. return
  6058. self.source_editor_tab.handleTextChanged()
  6059. self.source_editor_tab.t_frame.show()
  6060. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6061. self.proc_container.view.set_idle()
  6062. # self.ui.show()
  6063. def on_toggle_code_editor(self):
  6064. self.defaults.report_usage("on_toggle_code_editor()")
  6065. if self.toggle_codeeditor is False:
  6066. self.init_code_editor(name=_("Code Editor"))
  6067. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6068. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6069. self.text_editor_tab.buttonSave.clicked.disconnect()
  6070. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6071. else:
  6072. for idx in range(self.ui.plot_tab_area.count()):
  6073. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6074. self.ui.plot_tab_area.closeTab(idx)
  6075. break
  6076. self.toggle_codeeditor = False
  6077. def on_code_editor_close(self):
  6078. self.toggle_codeeditor = False
  6079. def goto_text_line(self):
  6080. """
  6081. Will scroll a text to the specified text line.
  6082. :return: None
  6083. """
  6084. dia_box = Dialog_box(title=_("Go to Line ..."),
  6085. label=_("Line:"),
  6086. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6087. initial_text='')
  6088. try:
  6089. line = int(dia_box.location) - 1
  6090. except (ValueError, TypeError):
  6091. line = 0
  6092. if dia_box.ok:
  6093. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6094. # at the top of the window
  6095. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6096. # get the document() of the TextEditor
  6097. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6098. # create a Text Cursor based on the searched line
  6099. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6100. # set cursor of the code editor with the cursor at the searcehd line
  6101. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6102. def on_filenewscript(self, silent=False):
  6103. """
  6104. Will create a new script file and open it in the Code Editor
  6105. :param silent: if True will not display status messages
  6106. :return: None
  6107. """
  6108. if silent is False:
  6109. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6110. # delete the absolute and relative position and messages in the infobar
  6111. self.ui.position_label.setText("")
  6112. # self.ui.rel_position_label.setText("")
  6113. self.app_obj.new_script_object()
  6114. # script_text = script_obj.source_file
  6115. #
  6116. # self.proc_container.view.set_busy(_("Loading..."))
  6117. # script_obj.script_editor_tab.t_frame.hide()
  6118. #
  6119. # script_obj.script_editor_tab.t_frame.show()
  6120. # self.proc_container.view.set_idle()
  6121. def on_fileopenscript(self, name=None, silent=False):
  6122. """
  6123. Will open a Tcl script file into the Code Editor
  6124. :param silent: if True will not display status messages
  6125. :param name: name of a Tcl script file to open
  6126. :return: None
  6127. """
  6128. self.defaults.report_usage("on_fileopenscript")
  6129. App.log.debug("on_fileopenscript()")
  6130. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6131. "All Files (*.*)"
  6132. if name:
  6133. filenames = [name]
  6134. else:
  6135. try:
  6136. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6137. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6138. except TypeError:
  6139. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6140. if len(filenames) == 0:
  6141. if silent is False:
  6142. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6143. else:
  6144. for filename in filenames:
  6145. if filename != '':
  6146. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6147. def on_fileopenscript_example(self, name=None, silent=False):
  6148. """
  6149. Will open a Tcl script file into the Code Editor
  6150. :param silent: if True will not display status messages
  6151. :param name: name of a Tcl script file to open
  6152. :return:
  6153. """
  6154. self.defaults.report_usage("on_fileopenscript_example")
  6155. log.debug("on_fileopenscript_example()")
  6156. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6157. "All Files (*.*)"
  6158. # test if the app was frozen and choose the path for the configuration file
  6159. if getattr(sys, "frozen", False) is True:
  6160. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6161. else:
  6162. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6163. if name:
  6164. filenames = [name]
  6165. else:
  6166. try:
  6167. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6168. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6169. except TypeError:
  6170. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6171. if len(filenames) == 0:
  6172. if silent is False:
  6173. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6174. else:
  6175. for filename in filenames:
  6176. if filename != '':
  6177. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6178. def on_filerunscript(self, name=None, silent=False):
  6179. """
  6180. File menu callback for loading and running a TCL script.
  6181. :param silent: if True will not display status messages
  6182. :param name: name of a Tcl script file to be run by FlatCAM
  6183. :return: None
  6184. """
  6185. self.defaults.report_usage("on_filerunscript")
  6186. App.log.debug("on_file_runscript()")
  6187. if name:
  6188. filename = name
  6189. if self.cmd_line_headless != 1:
  6190. self.splash.showMessage('%s: %ssec\n%s' %
  6191. (_("Canvas initialization started.\n"
  6192. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6193. _("Executing ScriptObject file.")
  6194. ),
  6195. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6196. color=QtGui.QColor("gray"))
  6197. else:
  6198. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6199. "All Files (*.*)"
  6200. try:
  6201. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6202. directory=self.get_last_folder(), filter=_filter_)
  6203. except TypeError:
  6204. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6205. # The Qt methods above will return a QString which can cause problems later.
  6206. # So far json.dump() will fail to serialize it.
  6207. filename = str(filename)
  6208. if filename == "":
  6209. if silent is False:
  6210. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6211. else:
  6212. if self.cmd_line_headless != 1:
  6213. if self.ui.shell_dock.isHidden():
  6214. self.ui.shell_dock.show()
  6215. try:
  6216. with open(filename, "r") as tcl_script:
  6217. cmd_line_shellfile_content = tcl_script.read()
  6218. if self.cmd_line_headless != 1:
  6219. self.shell.exec_command(cmd_line_shellfile_content)
  6220. else:
  6221. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6222. if silent is False:
  6223. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6224. except Exception as e:
  6225. log.debug("App.on_filerunscript() -> %s" % str(e))
  6226. sys.exit(2)
  6227. def on_file_saveproject(self, silent=False):
  6228. """
  6229. Callback for menu item File->Save Project. Saves the project to
  6230. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6231. if set to None. The project is saved by calling ``self.save_project()``.
  6232. :param silent: if True will not display status messages
  6233. :return: None
  6234. """
  6235. self.defaults.report_usage("on_file_saveproject")
  6236. if self.project_filename is None:
  6237. self.on_file_saveprojectas()
  6238. else:
  6239. self.worker_task.emit({'fcn': self.save_project,
  6240. 'params': [self.project_filename, silent]})
  6241. if self.defaults["global_open_style"] is False:
  6242. self.file_opened.emit("project", self.project_filename)
  6243. self.file_saved.emit("project", self.project_filename)
  6244. self.set_ui_title(name=self.project_filename)
  6245. self.should_we_save = False
  6246. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6247. """
  6248. Callback for menu item File->Save Project As... Opens a file
  6249. chooser and saves the project to the given file via
  6250. ``self.save_project()``.
  6251. :param make_copy if to be create a copy of the project; boolean
  6252. :param use_thread: if to be run in a separate thread; boolean
  6253. :param quit_action: if to be followed by quiting the application; boolean
  6254. :return: None
  6255. """
  6256. self.defaults.report_usage("on_file_saveprojectas")
  6257. self.date = str(datetime.today()).rpartition('.')[0]
  6258. self.date = ''.join(c for c in self.date if c not in ':-')
  6259. self.date = self.date.replace(' ', '_')
  6260. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6261. try:
  6262. filename, _f = FCFileSaveDialog.get_saved_filename(
  6263. caption=_("Save Project As ..."),
  6264. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6265. proj=_("Project")),
  6266. filter=filter_
  6267. )
  6268. except TypeError:
  6269. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6270. filename = str(filename)
  6271. if filename == '':
  6272. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6273. return
  6274. if use_thread is True:
  6275. self.worker_task.emit({'fcn': self.save_project,
  6276. 'params': [filename, quit_action]})
  6277. else:
  6278. self.save_project(filename, quit_action)
  6279. # self.save_project(filename)
  6280. if self.defaults["global_open_style"] is False:
  6281. self.file_opened.emit("project", filename)
  6282. self.file_saved.emit("project", filename)
  6283. if not make_copy:
  6284. self.project_filename = filename
  6285. self.set_ui_title(name=self.project_filename)
  6286. self.should_we_save = False
  6287. def on_file_save_objects_pdf(self, use_thread=True):
  6288. self.date = str(datetime.today()).rpartition('.')[0]
  6289. self.date = ''.join(c for c in self.date if c not in ':-')
  6290. self.date = self.date.replace(' ', '_')
  6291. try:
  6292. obj_selection = self.collection.get_selected()
  6293. if len(obj_selection) == 1:
  6294. obj_name = str(obj_selection[0].options['name'])
  6295. else:
  6296. obj_name = _("FlatCAM objects print")
  6297. except AttributeError as err:
  6298. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6299. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6300. return
  6301. if not obj_selection:
  6302. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6303. return
  6304. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6305. try:
  6306. filename, _f = FCFileSaveDialog.get_saved_filename(
  6307. caption=_("Save Object as PDF ..."),
  6308. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6309. obj_name=obj_name,
  6310. date=self.date),
  6311. filter=filter_
  6312. )
  6313. except TypeError:
  6314. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6315. filename = str(filename)
  6316. if filename == '':
  6317. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6318. return
  6319. if use_thread is True:
  6320. self.proc_container.new(_("Printing PDF ... Please wait."))
  6321. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6322. else:
  6323. self.save_pdf(filename, obj_selection)
  6324. # self.save_project(filename)
  6325. if self.defaults["global_open_style"] is False:
  6326. self.file_opened.emit("pdf", filename)
  6327. self.file_saved.emit("pdf", filename)
  6328. def save_pdf(self, file_name, obj_selection):
  6329. p_size = self.defaults['global_workspaceT']
  6330. orientation = self.defaults['global_workspace_orientation']
  6331. color = 'black'
  6332. transparency_level = 1.0
  6333. self.pagesize = {}
  6334. self.pagesize.update(
  6335. {
  6336. 'Bounds': None,
  6337. 'A0': (841 * mm, 1189 * mm),
  6338. 'A1': (594 * mm, 841 * mm),
  6339. 'A2': (420 * mm, 594 * mm),
  6340. 'A3': (297 * mm, 420 * mm),
  6341. 'A4': (210 * mm, 297 * mm),
  6342. 'A5': (148 * mm, 210 * mm),
  6343. 'A6': (105 * mm, 148 * mm),
  6344. 'A7': (74 * mm, 105 * mm),
  6345. 'A8': (52 * mm, 74 * mm),
  6346. 'A9': (37 * mm, 52 * mm),
  6347. 'A10': (26 * mm, 37 * mm),
  6348. 'B0': (1000 * mm, 1414 * mm),
  6349. 'B1': (707 * mm, 1000 * mm),
  6350. 'B2': (500 * mm, 707 * mm),
  6351. 'B3': (353 * mm, 500 * mm),
  6352. 'B4': (250 * mm, 353 * mm),
  6353. 'B5': (176 * mm, 250 * mm),
  6354. 'B6': (125 * mm, 176 * mm),
  6355. 'B7': (88 * mm, 125 * mm),
  6356. 'B8': (62 * mm, 88 * mm),
  6357. 'B9': (44 * mm, 62 * mm),
  6358. 'B10': (31 * mm, 44 * mm),
  6359. 'C0': (917 * mm, 1297 * mm),
  6360. 'C1': (648 * mm, 917 * mm),
  6361. 'C2': (458 * mm, 648 * mm),
  6362. 'C3': (324 * mm, 458 * mm),
  6363. 'C4': (229 * mm, 324 * mm),
  6364. 'C5': (162 * mm, 229 * mm),
  6365. 'C6': (114 * mm, 162 * mm),
  6366. 'C7': (81 * mm, 114 * mm),
  6367. 'C8': (57 * mm, 81 * mm),
  6368. 'C9': (40 * mm, 57 * mm),
  6369. 'C10': (28 * mm, 40 * mm),
  6370. # American paper sizes
  6371. 'LETTER': (8.5 * inch, 11 * inch),
  6372. 'LEGAL': (8.5 * inch, 14 * inch),
  6373. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6374. # From https://en.wikipedia.org/wiki/Paper_size
  6375. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6376. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6377. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6378. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6379. 'LEDGER': (17 * inch, 11 * inch),
  6380. }
  6381. )
  6382. exported_svg = []
  6383. for obj in obj_selection:
  6384. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6385. scale_factor_x=None, scale_factor_y=None,
  6386. skew_factor_x=None, skew_factor_y=None,
  6387. mirror=None)
  6388. if obj.kind.lower() == 'gerber':
  6389. # color = self.defaults["gerber_plot_fill"][:-2]
  6390. color = obj.fill_color[:-2]
  6391. elif obj.kind.lower() == 'excellon':
  6392. color = '#C40000'
  6393. elif obj.kind.lower() == 'geometry':
  6394. color = self.defaults["global_draw_color"]
  6395. # Change the attributes of the exported SVG
  6396. # We don't need stroke-width
  6397. # We set opacity to maximum
  6398. # We set the colour to WHITE
  6399. root = ET.fromstring(svg_obj)
  6400. for child in root:
  6401. child.set('fill', str(color))
  6402. child.set('opacity', str(transparency_level))
  6403. child.set('stroke', str(color))
  6404. exported_svg.append(ET.tostring(root))
  6405. xmin = Inf
  6406. ymin = Inf
  6407. xmax = -Inf
  6408. ymax = -Inf
  6409. for obj in obj_selection:
  6410. try:
  6411. gxmin, gymin, gxmax, gymax = obj.bounds()
  6412. xmin = min([xmin, gxmin])
  6413. ymin = min([ymin, gymin])
  6414. xmax = max([xmax, gxmax])
  6415. ymax = max([ymax, gymax])
  6416. except Exception as e:
  6417. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6418. # Determine bounding area for svg export
  6419. bounds = [xmin, ymin, xmax, ymax]
  6420. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6421. # This contain the measure units
  6422. uom = obj_selection[0].units.lower()
  6423. # Define a boundary around SVG of about 1.0mm (~39mils)
  6424. if uom in "mm":
  6425. boundary = 1.0
  6426. else:
  6427. boundary = 0.0393701
  6428. # Convert everything to strings for use in the xml doc
  6429. svgwidth = str(size[0] + (2 * boundary))
  6430. svgheight = str(size[1] + (2 * boundary))
  6431. minx = str(bounds[0] - boundary)
  6432. miny = str(bounds[1] + boundary + size[1])
  6433. # Add a SVG Header and footer to the svg output from shapely
  6434. # The transform flips the Y Axis so that everything renders
  6435. # properly within svg apps such as inkscape
  6436. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6437. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6438. svg_header += 'width="' + svgwidth + uom + '" '
  6439. svg_header += 'height="' + svgheight + uom + '" '
  6440. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6441. svg_header += '>'
  6442. svg_header += '<g transform="scale(1,-1)">'
  6443. svg_footer = '</g> </svg>'
  6444. svg_elem = str(svg_header)
  6445. for svg_item in exported_svg:
  6446. svg_elem += str(svg_item)
  6447. svg_elem += str(svg_footer)
  6448. # Parse the xml through a xml parser just to add line feeds
  6449. # and to make it look more pretty for the output
  6450. doc = parse_xml_string(svg_elem)
  6451. doc_final = doc.toprettyxml()
  6452. try:
  6453. if self.defaults['units'].upper() == 'IN':
  6454. unit = inch
  6455. else:
  6456. unit = mm
  6457. doc_final = StringIO(doc_final)
  6458. drawing = svg2rlg(doc_final)
  6459. if p_size == 'Bounds':
  6460. renderPDF.drawToFile(drawing, file_name)
  6461. else:
  6462. if orientation == 'p':
  6463. page_size = portrait(self.pagesize[p_size])
  6464. else:
  6465. page_size = landscape(self.pagesize[p_size])
  6466. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6467. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6468. renderPDF.draw(drawing, my_canvas, 0, 0)
  6469. my_canvas.save()
  6470. except Exception as e:
  6471. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6472. return 'fail'
  6473. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6474. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6475. """
  6476. Exports a Geometry Object to an SVG file.
  6477. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6478. :param filename: Path to the SVG file to save to.
  6479. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6480. :return:
  6481. """
  6482. self.defaults.report_usage("export_svg()")
  6483. if filename is None:
  6484. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6485. is not None else self.defaults["global_last_folder"]
  6486. self.log.debug("export_svg()")
  6487. try:
  6488. obj = self.collection.get_by_name(str(obj_name))
  6489. except Exception:
  6490. # TODO: The return behavior has not been established... should raise exception?
  6491. return "Could not retrieve object: %s" % obj_name
  6492. with self.proc_container.new(_("Exporting SVG")) as proc:
  6493. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6494. # Determine bounding area for svg export
  6495. bounds = obj.bounds()
  6496. size = obj.size()
  6497. # Convert everything to strings for use in the xml doc
  6498. svgwidth = str(size[0])
  6499. svgheight = str(size[1])
  6500. minx = str(bounds[0])
  6501. miny = str(bounds[1] - size[1])
  6502. uom = obj.units.lower()
  6503. # Add a SVG Header and footer to the svg output from shapely
  6504. # The transform flips the Y Axis so that everything renders
  6505. # properly within svg apps such as inkscape
  6506. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6507. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6508. svg_header += 'width="' + svgwidth + uom + '" '
  6509. svg_header += 'height="' + svgheight + uom + '" '
  6510. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6511. svg_header += '<g transform="scale(1,-1)">'
  6512. svg_footer = '</g> </svg>'
  6513. svg_elem = svg_header + exported_svg + svg_footer
  6514. # Parse the xml through a xml parser just to add line feeds
  6515. # and to make it look more pretty for the output
  6516. svgcode = parse_xml_string(svg_elem)
  6517. svgcode = svgcode.toprettyxml()
  6518. try:
  6519. with open(filename, 'w') as fp:
  6520. fp.write(svgcode)
  6521. except PermissionError:
  6522. self.inform.emit('[WARNING] %s' %
  6523. _("Permission denied, saving not possible.\n"
  6524. "Most likely another app is holding the file open and not accessible."))
  6525. return 'fail'
  6526. if self.defaults["global_open_style"] is False:
  6527. self.file_opened.emit("SVG", filename)
  6528. self.file_saved.emit("SVG", filename)
  6529. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6530. def save_source_file(self, obj_name, filename, use_thread=True):
  6531. """
  6532. Exports a FlatCAM Object to an Gerber/Excellon file.
  6533. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6534. :param filename: Path to the Gerber file to save to.
  6535. :param use_thread: if to be run in a separate thread
  6536. :return:
  6537. """
  6538. self.defaults.report_usage("save source file()")
  6539. if filename is None:
  6540. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6541. is not None else self.defaults["global_last_folder"]
  6542. self.log.debug("save source file()")
  6543. obj = self.collection.get_by_name(obj_name)
  6544. file_string = StringIO(obj.source_file)
  6545. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6546. if file_string.getvalue() == '':
  6547. self.inform.emit('[ERROR_NOTCL] %s' %
  6548. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6549. return 'fail'
  6550. try:
  6551. with open(filename, 'w') as file:
  6552. file.writelines('G04*\n')
  6553. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6554. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6555. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6556. file.writelines('G04 Created on : %s*\n' % time_string)
  6557. for line in file_string:
  6558. file.writelines(line)
  6559. except PermissionError:
  6560. self.inform.emit('[WARNING] %s' %
  6561. _("Permission denied, saving not possible.\n"
  6562. "Most likely another app is holding the file open and not accessible."))
  6563. return 'fail'
  6564. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6565. """
  6566. Exports a Excellon Object to an Excellon file.
  6567. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6568. :param filename: Path to the Excellon file to save to.
  6569. :param local_use:
  6570. :param use_thread: if to be run in a separate thread
  6571. :return:
  6572. """
  6573. self.defaults.report_usage("export_excellon()")
  6574. if filename is None:
  6575. if self.defaults["global_last_save_folder"]:
  6576. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6577. else:
  6578. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6579. self.log.debug("export_excellon()")
  6580. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6581. self.defaults["excellon_exp_decimals"]
  6582. )
  6583. if local_use is None:
  6584. try:
  6585. obj = self.collection.get_by_name(str(obj_name))
  6586. except Exception:
  6587. return "Could not retrieve object: %s" % obj_name
  6588. else:
  6589. obj = local_use
  6590. if not isinstance(obj, ExcellonObject):
  6591. self.inform.emit('[ERROR_NOTCL] %s' %
  6592. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6593. return
  6594. # updated units
  6595. eunits = self.defaults["excellon_exp_units"]
  6596. ewhole = self.defaults["excellon_exp_integer"]
  6597. efract = self.defaults["excellon_exp_decimals"]
  6598. ezeros = self.defaults["excellon_exp_zeros"]
  6599. eformat = self.defaults["excellon_exp_format"]
  6600. slot_type = self.defaults["excellon_exp_slot_type"]
  6601. fc_units = self.defaults['units'].upper()
  6602. if fc_units == 'MM':
  6603. factor = 1 if eunits == 'METRIC' else 0.03937
  6604. else:
  6605. factor = 25.4 if eunits == 'METRIC' else 1
  6606. def make_excellon():
  6607. try:
  6608. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6609. header = 'M48\n'
  6610. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6611. (str(self.version), str(self.version_date))
  6612. header += ';Filename: %s' % str(obj_name) + '\n'
  6613. header += ';Created on : %s' % time_str + '\n'
  6614. if eformat == 'dec':
  6615. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6616. header += eunits + '\n'
  6617. for tool in obj.tools:
  6618. if eunits == 'METRIC':
  6619. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6620. tool=str(tool),
  6621. dec=2)
  6622. else:
  6623. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6624. tool=str(tool),
  6625. dec=4)
  6626. else:
  6627. if ezeros == 'LZ':
  6628. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6629. form='ndec', e_zeros='LZ', factor=factor,
  6630. slot_type=slot_type)
  6631. header += '%s,%s\n' % (eunits, 'LZ')
  6632. header += format_exc
  6633. for tool in obj.tools:
  6634. if eunits == 'METRIC':
  6635. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6636. tool=str(tool),
  6637. dec=2)
  6638. else:
  6639. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6640. tool=str(tool),
  6641. dec=4)
  6642. else:
  6643. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6644. form='ndec', e_zeros='TZ', factor=factor,
  6645. slot_type=slot_type)
  6646. header += '%s,%s\n' % (eunits, 'TZ')
  6647. header += format_exc
  6648. for tool in obj.tools:
  6649. if eunits == 'METRIC':
  6650. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6651. tool=str(tool),
  6652. dec=2)
  6653. else:
  6654. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6655. tool=str(tool),
  6656. dec=4)
  6657. header += '%\n'
  6658. footer = 'M30\n'
  6659. exported_excellon = header
  6660. exported_excellon += excellon_code
  6661. exported_excellon += footer
  6662. if local_use is None:
  6663. try:
  6664. with open(filename, 'w') as fp:
  6665. fp.write(exported_excellon)
  6666. except PermissionError:
  6667. self.inform.emit('[WARNING] %s' %
  6668. _("Permission denied, saving not possible.\n"
  6669. "Most likely another app is holding the file open and not accessible."))
  6670. return 'fail'
  6671. if self.defaults["global_open_style"] is False:
  6672. self.file_opened.emit("Excellon", filename)
  6673. self.file_saved.emit("Excellon", filename)
  6674. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6675. else:
  6676. return exported_excellon
  6677. except Exception as e:
  6678. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6679. return 'fail'
  6680. if use_thread is True:
  6681. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6682. def job_thread_exc(app_obj):
  6683. ret = make_excellon()
  6684. if ret == 'fail':
  6685. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6686. return
  6687. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6688. else:
  6689. eret = make_excellon()
  6690. if eret == 'fail':
  6691. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6692. return 'fail'
  6693. if local_use is not None:
  6694. return eret
  6695. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6696. """
  6697. Exports a Gerber Object to an Gerber file.
  6698. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6699. :param filename: Path to the Gerber file to save to.
  6700. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6701. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6702. :param use_thread: if to be run in a separate thread
  6703. :return:
  6704. """
  6705. self.defaults.report_usage("export_gerber()")
  6706. if filename is None:
  6707. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6708. is not None else self.defaults["global_last_folder"]
  6709. self.log.debug("export_gerber()")
  6710. if local_use is None:
  6711. try:
  6712. obj = self.collection.get_by_name(str(obj_name))
  6713. except Exception:
  6714. return "Could not retrieve object: %s" % obj_name
  6715. else:
  6716. obj = local_use
  6717. # updated units
  6718. gunits = self.defaults["gerber_exp_units"]
  6719. gwhole = self.defaults["gerber_exp_integer"]
  6720. gfract = self.defaults["gerber_exp_decimals"]
  6721. gzeros = self.defaults["gerber_exp_zeros"]
  6722. fc_units = self.defaults['units'].upper()
  6723. if fc_units == 'MM':
  6724. factor = 1 if gunits == 'MM' else 0.03937
  6725. else:
  6726. factor = 25.4 if gunits == 'MM' else 1
  6727. def make_gerber():
  6728. try:
  6729. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6730. header = 'G04*\n'
  6731. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6732. (str(self.version), str(self.version_date))
  6733. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6734. header += 'G04 Created on : %s*' % time_str + '\n'
  6735. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6736. header += "%MO{units}*%\n".format(units=gunits)
  6737. for apid in obj.apertures:
  6738. if obj.apertures[apid]['type'] == 'C':
  6739. header += "%ADD{apid}{type},{size}*%\n".format(
  6740. apid=str(apid),
  6741. type='C',
  6742. size=(factor * obj.apertures[apid]['size'])
  6743. )
  6744. elif obj.apertures[apid]['type'] == 'R':
  6745. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6746. apid=str(apid),
  6747. type='R',
  6748. width=(factor * obj.apertures[apid]['width']),
  6749. height=(factor * obj.apertures[apid]['height'])
  6750. )
  6751. elif obj.apertures[apid]['type'] == 'O':
  6752. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6753. apid=str(apid),
  6754. type='O',
  6755. width=(factor * obj.apertures[apid]['width']),
  6756. height=(factor * obj.apertures[apid]['height'])
  6757. )
  6758. header += '\n'
  6759. # obsolete units but some software may need it
  6760. if gunits == 'IN':
  6761. header += 'G70*\n'
  6762. else:
  6763. header += 'G71*\n'
  6764. # Absolute Mode
  6765. header += 'G90*\n'
  6766. header += 'G01*\n'
  6767. # positive polarity
  6768. header += '%LPD*%\n'
  6769. footer = 'M02*\n'
  6770. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6771. exported_gerber = header
  6772. exported_gerber += gerber_code
  6773. exported_gerber += footer
  6774. if local_use is None:
  6775. try:
  6776. with open(filename, 'w') as fp:
  6777. fp.write(exported_gerber)
  6778. except PermissionError:
  6779. self.inform.emit('[WARNING] %s' %
  6780. _("Permission denied, saving not possible.\n"
  6781. "Most likely another app is holding the file open and not accessible."))
  6782. return 'fail'
  6783. if self.defaults["global_open_style"] is False:
  6784. self.file_opened.emit("Gerber", filename)
  6785. self.file_saved.emit("Gerber", filename)
  6786. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6787. else:
  6788. return exported_gerber
  6789. except Exception as e:
  6790. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6791. return 'fail'
  6792. if use_thread is True:
  6793. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6794. def job_thread_grb(app_obj):
  6795. ret = make_gerber()
  6796. if ret == 'fail':
  6797. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6798. return
  6799. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6800. else:
  6801. gret = make_gerber()
  6802. if gret == 'fail':
  6803. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6804. return 'fail'
  6805. if local_use is not None:
  6806. return gret
  6807. def export_dxf(self, obj_name, filename, use_thread=True):
  6808. """
  6809. Exports a Geometry Object to an DXF file.
  6810. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6811. :param filename: Path to the DXF file to save to.
  6812. :param use_thread: if to be run in a separate thread
  6813. :return:
  6814. """
  6815. self.defaults.report_usage("export_dxf()")
  6816. if filename is None:
  6817. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6818. is not None else self.defaults["global_last_folder"]
  6819. self.log.debug("export_dxf()")
  6820. try:
  6821. obj = self.collection.get_by_name(str(obj_name))
  6822. except Exception:
  6823. # TODO: The return behavior has not been established... should raise exception?
  6824. return "Could not retrieve object: %s" % obj_name
  6825. def make_dxf():
  6826. try:
  6827. dxf_code = obj.export_dxf()
  6828. dxf_code.saveas(filename)
  6829. if self.defaults["global_open_style"] is False:
  6830. self.file_opened.emit("DXF", filename)
  6831. self.file_saved.emit("DXF", filename)
  6832. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6833. except Exception:
  6834. return 'fail'
  6835. if use_thread is True:
  6836. with self.proc_container.new(_("Exporting DXF")) as proc:
  6837. def job_thread_exc(app_obj):
  6838. ret_dxf_val = make_dxf()
  6839. if ret_dxf_val == 'fail':
  6840. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6841. return
  6842. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6843. else:
  6844. ret = make_dxf()
  6845. if ret == 'fail':
  6846. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6847. return
  6848. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6849. """
  6850. Adds a new Geometry Object to the projects and populates
  6851. it with shapes extracted from the SVG file.
  6852. :param plot: If True then the resulting object will be plotted on canvas
  6853. :param filename: Path to the SVG file.
  6854. :param geo_type: Type of FlatCAM object that will be created from SVG
  6855. :param outname: The name given to the resulting FlatCAM object
  6856. :return:
  6857. """
  6858. self.defaults.report_usage("import_svg()")
  6859. log.debug("App.import_svg()")
  6860. obj_type = ""
  6861. if geo_type is None or geo_type == "geometry":
  6862. obj_type = "geometry"
  6863. elif geo_type == "gerber":
  6864. obj_type = "gerber"
  6865. else:
  6866. self.inform.emit('[ERROR_NOTCL] %s' %
  6867. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6868. return
  6869. units = self.defaults['units'].upper()
  6870. def obj_init(geo_obj, app_obj):
  6871. geo_obj.import_svg(filename, obj_type, units=units)
  6872. geo_obj.multigeo = False
  6873. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6874. with self.proc_container.new(_("Importing SVG")) as proc:
  6875. # Object name
  6876. name = outname or filename.split('/')[-1].split('\\')[-1]
  6877. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6878. if ret == 'fail':
  6879. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6880. return 'fail'
  6881. # Register recent file
  6882. self.file_opened.emit("svg", filename)
  6883. # AppGUI feedback
  6884. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6885. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6886. """
  6887. Adds a new Geometry Object to the projects and populates
  6888. it with shapes extracted from the DXF file.
  6889. :param filename: Path to the DXF file.
  6890. :param geo_type: Type of FlatCAM object that will be created from DXF
  6891. :param outname: Name for the imported Geometry
  6892. :param plot: If True then the resulting object will be plotted on canvas
  6893. :return:
  6894. """
  6895. self.defaults.report_usage("import_dxf()")
  6896. obj_type = ""
  6897. if geo_type is None or geo_type == "geometry":
  6898. obj_type = "geometry"
  6899. elif geo_type == "gerber":
  6900. obj_type = geo_type
  6901. else:
  6902. self.inform.emit('[ERROR_NOTCL] %s' %
  6903. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6904. return
  6905. units = self.defaults['units'].upper()
  6906. def obj_init(geo_obj, app_obj):
  6907. geo_obj.import_dxf(filename, obj_type, units=units)
  6908. geo_obj.multigeo = False
  6909. with self.proc_container.new(_("Importing DXF")):
  6910. # Object name
  6911. name = outname or filename.split('/')[-1].split('\\')[-1]
  6912. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6913. if ret == 'fail':
  6914. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6915. return 'fail'
  6916. # Register recent file
  6917. self.file_opened.emit("dxf", filename)
  6918. # AppGUI feedback
  6919. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6920. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6921. """
  6922. Opens a Gerber file, parses it and creates a new object for
  6923. it in the program. Thread-safe.
  6924. :param outname: Name of the resulting object. None causes the
  6925. name to be that of the file. Str.
  6926. :param filename: Gerber file filename
  6927. :type filename: str
  6928. :param plot: boolean, to plot or not the resulting object
  6929. :param from_tcl: True if run from Tcl Shell
  6930. :return: None
  6931. """
  6932. # How the object should be initialized
  6933. def obj_init(gerber_obj, app_obj):
  6934. assert isinstance(gerber_obj, GerberObject), \
  6935. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6936. # Opening the file happens here
  6937. try:
  6938. gerber_obj.parse_file(filename)
  6939. except IOError:
  6940. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6941. return "fail"
  6942. except ParseError as err:
  6943. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6944. app_obj.log.error(str(err))
  6945. return "fail"
  6946. except Exception as e:
  6947. log.debug("App.open_gerber() --> %s" % str(e))
  6948. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6949. msg += traceback.format_exc()
  6950. app_obj.inform.emit(msg)
  6951. return "fail"
  6952. if gerber_obj.is_empty():
  6953. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6954. _("Object is not Gerber file or empty. Aborting object creation."))
  6955. return "fail"
  6956. App.log.debug("open_gerber()")
  6957. with self.proc_container.new(_("Opening Gerber")):
  6958. # Object name
  6959. name = outname or filename.split('/')[-1].split('\\')[-1]
  6960. # # ## Object creation # ##
  6961. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6962. if ret_val == 'fail':
  6963. if from_tcl:
  6964. filename = self.defaults['global_tcl_path'] + '/' + name
  6965. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6966. if ret_val == 'fail':
  6967. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6968. return 'fail'
  6969. # Register recent file
  6970. self.file_opened.emit("gerber", filename)
  6971. # AppGUI feedback
  6972. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6973. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6974. """
  6975. Opens an Excellon file, parses it and creates a new object for
  6976. it in the program. Thread-safe.
  6977. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6978. :param filename: Excellon file filename
  6979. :type filename: str
  6980. :param plot: boolean, to plot or not the resulting object
  6981. :param from_tcl: True if run from Tcl Shell
  6982. :return: None
  6983. """
  6984. App.log.debug("open_excellon()")
  6985. # How the object should be initialized
  6986. def obj_init(excellon_obj, app_obj):
  6987. try:
  6988. ret = excellon_obj.parse_file(filename=filename)
  6989. if ret == "fail":
  6990. log.debug("Excellon parsing failed.")
  6991. self.inform.emit('[ERROR_NOTCL] %s' %
  6992. _("This is not Excellon file."))
  6993. return "fail"
  6994. except IOError:
  6995. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6996. (_("Cannot open file"), filename))
  6997. log.debug("Could not open Excellon object.")
  6998. return "fail"
  6999. except Exception:
  7000. msg = '[ERROR_NOTCL] %s' % \
  7001. _("An internal error has occurred. See shell.\n")
  7002. msg += traceback.format_exc()
  7003. app_obj.inform.emit(msg)
  7004. return "fail"
  7005. ret = excellon_obj.create_geometry()
  7006. if ret == 'fail':
  7007. log.debug("Could not create geometry for Excellon object.")
  7008. return "fail"
  7009. for tool in excellon_obj.tools:
  7010. if excellon_obj.tools[tool]['solid_geometry']:
  7011. return
  7012. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7013. return "fail"
  7014. with self.proc_container.new(_("Opening Excellon.")):
  7015. # Object name
  7016. name = outname or filename.split('/')[-1].split('\\')[-1]
  7017. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7018. if ret_val == 'fail':
  7019. if from_tcl:
  7020. filename = self.defaults['global_tcl_path'] + '/' + name
  7021. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7022. if ret_val == 'fail':
  7023. self.inform.emit('[ERROR_NOTCL] %s' %
  7024. _('Open Excellon file failed. Probable not an Excellon file.'))
  7025. return
  7026. # Register recent file
  7027. self.file_opened.emit("excellon", filename)
  7028. # AppGUI feedback
  7029. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7030. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7031. """
  7032. Opens a G-gcode file, parses it and creates a new object for
  7033. it in the program. Thread-safe.
  7034. :param filename: G-code file filename
  7035. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7036. :param force_parsing:
  7037. :param plot: If True plot the object on canvas
  7038. :param from_tcl: True if run from Tcl Shell
  7039. :return: None
  7040. """
  7041. App.log.debug("open_gcode()")
  7042. # How the object should be initialized
  7043. def obj_init(job_obj, app_obj_):
  7044. """
  7045. :param job_obj: the resulting object
  7046. :type app_obj_: App
  7047. """
  7048. assert isinstance(app_obj_, App), \
  7049. "Initializer expected App, got %s" % type(app_obj_)
  7050. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7051. try:
  7052. f = open(filename)
  7053. gcode = f.read()
  7054. f.close()
  7055. except IOError:
  7056. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7057. return "fail"
  7058. job_obj.gcode = gcode
  7059. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7060. if gcode_ret == "fail":
  7061. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7062. return "fail"
  7063. job_obj.create_geometry()
  7064. with self.proc_container.new(_("Opening G-Code.")):
  7065. # Object name
  7066. name = outname or filename.split('/')[-1].split('\\')[-1]
  7067. # New object creation and file processing
  7068. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7069. if ret_val == 'fail':
  7070. if from_tcl:
  7071. filename = self.defaults['global_tcl_path'] + '/' + name
  7072. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7073. if ret_val == 'fail':
  7074. self.inform.emit('[ERROR_NOTCL] %s' %
  7075. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7076. "Try to load it from File menu.\n "
  7077. "Attempting to create a FlatCAM CNCJob Object from "
  7078. "G-Code file failed during processing"))
  7079. return "fail"
  7080. # Register recent file
  7081. self.file_opened.emit("cncjob", filename)
  7082. # AppGUI feedback
  7083. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7084. def open_hpgl2(self, filename, outname=None):
  7085. """
  7086. Opens a HPGL2 file, parses it and creates a new object for
  7087. it in the program. Thread-safe.
  7088. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7089. :param filename: HPGL2 file filename
  7090. :return: None
  7091. """
  7092. filename = filename
  7093. # How the object should be initialized
  7094. def obj_init(geo_obj, app_obj):
  7095. assert isinstance(geo_obj, GeometryObject), \
  7096. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7097. # Opening the file happens here
  7098. obj = HPGL2(self)
  7099. try:
  7100. HPGL2.parse_file(obj, filename)
  7101. except IOError:
  7102. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7103. return "fail"
  7104. except ParseError as err:
  7105. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7106. app_obj.log.error(str(err))
  7107. return "fail"
  7108. except Exception as e:
  7109. log.debug("App.open_hpgl2() --> %s" % str(e))
  7110. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7111. msg += traceback.format_exc()
  7112. app_obj.inform.emit(msg)
  7113. return "fail"
  7114. geo_obj.multigeo = True
  7115. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7116. geo_obj.tools = deepcopy(obj.tools)
  7117. geo_obj.source_file = deepcopy(obj.source_file)
  7118. del obj
  7119. if not geo_obj.solid_geometry:
  7120. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7121. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7122. return "fail"
  7123. App.log.debug("open_hpgl2()")
  7124. with self.proc_container.new(_("Opening HPGL2")):
  7125. # Object name
  7126. name = outname or filename.split('/')[-1].split('\\')[-1]
  7127. # # ## Object creation # ##
  7128. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7129. if ret == 'fail':
  7130. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7131. return 'fail'
  7132. # Register recent file
  7133. self.file_opened.emit("geometry", filename)
  7134. # AppGUI feedback
  7135. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7136. def open_script(self, filename, outname=None, silent=False):
  7137. """
  7138. Opens a Script file, parses it and creates a new object for
  7139. it in the program. Thread-safe.
  7140. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7141. :param filename: Script file filename
  7142. :param silent: If True there will be no messages printed to StatusBar
  7143. :return: None
  7144. """
  7145. def obj_init(script_obj, app_obj):
  7146. assert isinstance(script_obj, ScriptObject), \
  7147. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7148. if silent is False:
  7149. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7150. try:
  7151. script_obj.parse_file(filename)
  7152. except IOError:
  7153. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7154. return "fail"
  7155. except ParseError as err:
  7156. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7157. app_obj.log.error(str(err))
  7158. return "fail"
  7159. except Exception as e:
  7160. log.debug("App.open_script() -> %s" % str(e))
  7161. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7162. msg += traceback.format_exc()
  7163. app_obj.inform.emit(msg)
  7164. return "fail"
  7165. App.log.debug("open_script()")
  7166. with self.proc_container.new(_("Opening TCL Script...")):
  7167. # Object name
  7168. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7169. # Object creation
  7170. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7171. if ret_val == 'fail':
  7172. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7173. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7174. if ret_val == 'fail':
  7175. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7176. return 'fail'
  7177. # Register recent file
  7178. self.file_opened.emit("script", filename)
  7179. # AppGUI feedback
  7180. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7181. def open_config_file(self, filename, run_from_arg=None):
  7182. """
  7183. Loads a config file from the specified file.
  7184. :param filename: Name of the file from which to load.
  7185. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7186. :return: None
  7187. """
  7188. App.log.debug("Opening config file: " + filename)
  7189. if run_from_arg:
  7190. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7191. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7192. _("Opening FlatCAM Config file.")),
  7193. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7194. color=QtGui.QColor("gray"))
  7195. # # add the tab if it was closed
  7196. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7197. # # first clear previous text in text editor (if any)
  7198. # self.ui.text_editor_tab.code_editor.clear()
  7199. #
  7200. # # Switch plot_area to CNCJob tab
  7201. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7202. # close the Code editor if already open
  7203. if self.toggle_codeeditor:
  7204. self.on_toggle_code_editor()
  7205. self.on_toggle_code_editor()
  7206. try:
  7207. if filename:
  7208. f = QtCore.QFile(filename)
  7209. if f.open(QtCore.QIODevice.ReadOnly):
  7210. stream = QtCore.QTextStream(f)
  7211. code_edited = stream.readAll()
  7212. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7213. f.close()
  7214. except IOError:
  7215. App.log.error("Failed to open config file: %s" % filename)
  7216. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7217. (_("Failed to open config file"), filename))
  7218. return
  7219. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7220. """
  7221. Loads a project from the specified file.
  7222. 1) Loads and parses file
  7223. 2) Registers the file as recently opened.
  7224. 3) Calls on_file_new()
  7225. 4) Updates options
  7226. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7227. 6) Calls plot_all() if plot=True
  7228. :param filename: Name of the file from which to load.
  7229. :param run_from_arg: True if run for arguments
  7230. :param plot: If True plot all objects in the project
  7231. :param cli: Run from command line
  7232. :param from_tcl: True if run from Tcl Sehll
  7233. :return: None
  7234. """
  7235. App.log.debug("Opening project: " + filename)
  7236. # block autosaving while a project is loaded
  7237. self.block_autosave = True
  7238. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7239. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7240. if cli is None:
  7241. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7242. if run_from_arg:
  7243. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7244. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7245. _("Opening FlatCAM Project file.")),
  7246. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7247. color=QtGui.QColor("gray"))
  7248. # Open and parse an uncompressed Project file
  7249. try:
  7250. f = open(filename, 'r')
  7251. except IOError:
  7252. if from_tcl:
  7253. name = filename.split('/')[-1].split('\\')[-1]
  7254. filename = self.defaults['global_tcl_path'] + '/' + name
  7255. try:
  7256. f = open(filename, 'r')
  7257. except IOError:
  7258. log.error("Failed to open project file: %s" % filename)
  7259. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7260. return
  7261. else:
  7262. log.error("Failed to open project file: %s" % filename)
  7263. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7264. return
  7265. try:
  7266. d = json.load(f, object_hook=dict2obj)
  7267. except Exception as e:
  7268. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7269. (filename, str(e)))
  7270. f.close()
  7271. # Open and parse a compressed Project file
  7272. try:
  7273. with lzma.open(filename) as f:
  7274. file_content = f.read().decode('utf-8')
  7275. d = json.loads(file_content, object_hook=dict2obj)
  7276. except Exception as e:
  7277. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7278. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7279. return
  7280. # Clear the current project
  7281. # # NOT THREAD SAFE # ##
  7282. if run_from_arg is True:
  7283. pass
  7284. elif cli is True:
  7285. self.delete_selection_shape()
  7286. else:
  7287. self.on_file_new()
  7288. # Project options
  7289. self.options.update(d['options'])
  7290. self.project_filename = filename
  7291. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7292. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7293. if cli is None:
  7294. self.set_screen_units(self.options["units"])
  7295. # Re create objects
  7296. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7297. for obj in d['objs']:
  7298. try:
  7299. def obj_init(obj_inst, app_inst):
  7300. obj_inst.from_dict(obj)
  7301. App.log.debug("Recreating from opened project an %s object: %s" %
  7302. (obj['kind'].capitalize(), obj['options']['name']))
  7303. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7304. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7305. if cli is None:
  7306. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7307. obj['kind'].upper(),
  7308. obj['options']['name']
  7309. )
  7310. )
  7311. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7312. except Exception as e:
  7313. print('App.open_project() --> ' + str(e))
  7314. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7315. self.should_we_save = False
  7316. self.file_opened.emit("project", filename)
  7317. # restore autosaving after a project was loaded
  7318. self.block_autosave = False
  7319. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7320. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7321. if cli is None:
  7322. self.set_ui_title(name=self.project_filename)
  7323. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7324. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7325. """
  7326. Re-generates all plots from all objects.
  7327. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7328. :param muted: if True don't print messages
  7329. :param use_thread: if True will use threading for plotting the objects
  7330. :return: None
  7331. """
  7332. self.log.debug("Plot_all()")
  7333. if muted is not True:
  7334. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7335. for plot_obj in self.collection.get_list():
  7336. def worker_task(obj):
  7337. with self.proc_container.new("Plotting"):
  7338. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7339. if fit_view is True:
  7340. self.app_obj.object_plotted.emit(obj)
  7341. if use_thread is True:
  7342. # Send to worker
  7343. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7344. else:
  7345. worker_task(plot_obj)
  7346. def register_folder(self, filename):
  7347. """
  7348. Register the last folder used by the app to open something
  7349. :param filename: the last folder is extracted from the filename
  7350. :return: None
  7351. """
  7352. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7353. def register_save_folder(self, filename):
  7354. """
  7355. Register the last folder used by the app to save something
  7356. :param filename: the last folder is extracted from the filename
  7357. :return: None
  7358. """
  7359. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7360. # def set_progress_bar(self, percentage, text=""):
  7361. # """
  7362. # Set a progress bar to a value (percentage)
  7363. #
  7364. # :param percentage: Value set to the progressbar
  7365. # :param text: Not used
  7366. # :return: None
  7367. # """
  7368. # self.ui.progress_bar.setValue(int(percentage))
  7369. def setup_recent_items(self):
  7370. """
  7371. Setup a dictionary with the recent files accessed, organized by type
  7372. :return:
  7373. """
  7374. icons = {
  7375. "gerber": self.resource_location + "/flatcam_icon16.png",
  7376. "excellon": self.resource_location + "/drill16.png",
  7377. 'geometry': self.resource_location + "/geometry16.png",
  7378. "cncjob": self.resource_location + "/cnc16.png",
  7379. "script": self.resource_location + "/script_new24.png",
  7380. "document": self.resource_location + "/notes16_1.png",
  7381. "project": self.resource_location + "/project16.png",
  7382. "svg": self.resource_location + "/geometry16.png",
  7383. "dxf": self.resource_location + "/dxf16.png",
  7384. "pdf": self.resource_location + "/pdf32.png",
  7385. "image": self.resource_location + "/image16.png"
  7386. }
  7387. try:
  7388. image_opener = self.image_tool.import_image
  7389. except AttributeError:
  7390. image_opener = None
  7391. openers = {
  7392. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7393. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7394. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7395. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7396. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7397. "document": None,
  7398. 'project': self.open_project,
  7399. 'svg': self.import_svg,
  7400. 'dxf': self.import_dxf,
  7401. 'image': image_opener,
  7402. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7403. }
  7404. # Open recent file for files
  7405. try:
  7406. f = open(self.data_path + '/recent.json')
  7407. except IOError:
  7408. App.log.error("Failed to load recent item list.")
  7409. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7410. return
  7411. try:
  7412. self.recent = json.load(f)
  7413. except json.errors.JSONDecodeError:
  7414. App.log.error("Failed to parse recent item list.")
  7415. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7416. f.close()
  7417. return
  7418. f.close()
  7419. # Open recent file for projects
  7420. try:
  7421. fp = open(self.data_path + '/recent_projects.json')
  7422. except IOError:
  7423. App.log.error("Failed to load recent project item list.")
  7424. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7425. return
  7426. try:
  7427. self.recent_projects = json.load(fp)
  7428. except json.errors.JSONDecodeError:
  7429. App.log.error("Failed to parse recent project item list.")
  7430. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7431. fp.close()
  7432. return
  7433. fp.close()
  7434. # Closure needed to create callbacks in a loop.
  7435. # Otherwise late binding occurs.
  7436. def make_callback(func, fname):
  7437. def opener():
  7438. func(fname)
  7439. return opener
  7440. def reset_recent_files():
  7441. # Reset menu
  7442. self.ui.recent.clear()
  7443. self.recent = []
  7444. try:
  7445. ff = open(self.data_path + '/recent.json', 'w')
  7446. except IOError:
  7447. App.log.error("Failed to open recent items file for writing.")
  7448. return
  7449. json.dump(self.recent, ff)
  7450. def reset_recent_projects():
  7451. # Reset menu
  7452. self.ui.recent_projects.clear()
  7453. self.recent_projects = []
  7454. try:
  7455. frp = open(self.data_path + '/recent_projects.json', 'w')
  7456. except IOError:
  7457. App.log.error("Failed to open recent projects items file for writing.")
  7458. return
  7459. json.dump(self.recent, frp)
  7460. # Reset menu
  7461. self.ui.recent.clear()
  7462. self.ui.recent_projects.clear()
  7463. # Create menu items for projects
  7464. for recent in self.recent_projects:
  7465. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7466. if recent['kind'] == 'project':
  7467. try:
  7468. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7469. # Attach callback
  7470. o = make_callback(openers[recent["kind"]], recent['filename'])
  7471. action.triggered.connect(o)
  7472. self.ui.recent_projects.addAction(action)
  7473. except KeyError:
  7474. App.log.error("Unsupported file type: %s" % recent["kind"])
  7475. # Last action in Recent Files menu is one that Clear the content
  7476. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7477. (_("Clear Recent projects")), self)
  7478. clear_action_proj.triggered.connect(reset_recent_projects)
  7479. self.ui.recent_projects.addSeparator()
  7480. self.ui.recent_projects.addAction(clear_action_proj)
  7481. # Create menu items for files
  7482. for recent in self.recent:
  7483. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7484. if recent['kind'] != 'project':
  7485. try:
  7486. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7487. # Attach callback
  7488. o = make_callback(openers[recent["kind"]], recent['filename'])
  7489. action.triggered.connect(o)
  7490. self.ui.recent.addAction(action)
  7491. except KeyError:
  7492. App.log.error("Unsupported file type: %s" % recent["kind"])
  7493. # Last action in Recent Files menu is one that Clear the content
  7494. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7495. (_("Clear Recent files")), self)
  7496. clear_action.triggered.connect(reset_recent_files)
  7497. self.ui.recent.addSeparator()
  7498. self.ui.recent.addAction(clear_action)
  7499. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7500. # self.ui.menufilerecent.set_submenu(recent_menu)
  7501. # recent_menu.show_all()
  7502. # self.ui.recent.show()
  7503. self.log.debug("Recent items list has been populated.")
  7504. def setup_component_editor(self):
  7505. """
  7506. Default text for the Selected tab when is not taken by the Object UI.
  7507. :return:
  7508. """
  7509. # label = QtWidgets.QLabel("Choose an item from Project")
  7510. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7511. sel_title = QtWidgets.QTextEdit(
  7512. _('<b>Shortcut Key List</b>'))
  7513. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7514. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7515. f_settings = QSettings("Open Source", "FlatCAM")
  7516. if f_settings.contains("notebook_font_size"):
  7517. fsize = f_settings.value('notebook_font_size', type=int)
  7518. else:
  7519. fsize = 12
  7520. tsize = fsize + int(fsize / 2)
  7521. # selected_text = (_('''
  7522. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7523. # </p>
  7524. #
  7525. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7526. # The normal flow when working in FlatCAM is the following:</span></p>
  7527. #
  7528. # <ol>
  7529. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7530. # file into
  7531. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7532. # even dragging and dropping the files on the AppGUI.<br />
  7533. # <br />
  7534. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7535. # drop of the
  7536. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7537. # &nbsp;</li>
  7538. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7539. # and then
  7540. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7541. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7542. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7543. # <br />
  7544. # If the selection of the object is done on the canvas by single click instead, and the
  7545. # <strong>SELECTED TAB</strong>
  7546. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7547. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7548. # it even if it was out of focus.<br />
  7549. # <br />
  7550. # You can change the parameters in this screen and the flow direction is like this:<br />
  7551. # <br />
  7552. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7553. # <strong> Geometry Object
  7554. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7555. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7556. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7557. # </ol>
  7558. #
  7559. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7560. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7561. # <strong>F3</strong>.</span></p>
  7562. #
  7563. # ''').format(fsize=fsize, tsize=tsize))
  7564. selected_text = '''
  7565. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7566. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7567. {s1}</span></p>
  7568. <ol>
  7569. <li><span style="font-size:{fsize}px">{s2}<br />
  7570. <br />
  7571. {s3}</span><br />
  7572. &nbsp;</li>
  7573. <li><span style="font-size:{fsize}px">{s4}<br />
  7574. &nbsp;</li>
  7575. <br />
  7576. <li><span style="font-size:{fsize}px">{s5}<br />
  7577. &nbsp;</li>
  7578. <br />
  7579. <li><span style="font-size:{fsize}px">{s6}<br />
  7580. <br />
  7581. {s7}</span></li>
  7582. </ol>
  7583. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7584. '''.format(
  7585. title=_("Selected Tab - Choose an Item from Project Tab"),
  7586. subtitle=_("Details"),
  7587. s1=_("The normal flow when working in FlatCAM is the following:"),
  7588. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7589. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7590. "files on the AppGUI."),
  7591. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7592. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7593. "actions offered within the app."),
  7594. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7595. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7596. "SELECTED TAB will be updated with the object properties according to its kind: "
  7597. "Gerber, Excellon, Geometry or CNCJob object."),
  7598. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7599. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7600. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7601. "the SELECTED TAB and populate it even if it was out of focus."),
  7602. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7603. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7604. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7605. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7606. "(again, done in SELECTED TAB) --> Save GCode."),
  7607. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7608. "or through its own key shortcut: <b>F3</b>."),
  7609. tsize=tsize,
  7610. fsize=fsize
  7611. )
  7612. sel_title.setText(selected_text)
  7613. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7614. self.ui.selected_scroll_area.setWidget(sel_title)
  7615. def setup_obj_classes(self):
  7616. """
  7617. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7618. class.
  7619. :return: None
  7620. """
  7621. FlatCAMObj.app = self
  7622. ObjectCollection.app = self
  7623. Gerber.app = self
  7624. Excellon.app = self
  7625. Geometry.app = self
  7626. CNCjob.app = self
  7627. FCProcess.app = self
  7628. FCProcessContainer.app = self
  7629. OptionsGroupUI.app = self
  7630. def version_check(self):
  7631. """
  7632. Checks for the latest version of the program. Alerts the
  7633. user if theirs is outdated. This method is meant to be run
  7634. in a separate thread.
  7635. :return: None
  7636. """
  7637. self.log.debug("version_check()")
  7638. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7639. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7640. App.version_url,
  7641. str(self.defaults['global_serial']),
  7642. str(self.version),
  7643. str(self.os),
  7644. urllib.parse.urlencode(self.defaults["global_stats"])
  7645. )
  7646. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7647. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7648. # urllib.parse.urlencode(self.defaults["global_stats"])
  7649. else:
  7650. # no_stats dict; just so it won't break things on website
  7651. no_ststs_dict = {}
  7652. no_ststs_dict["global_ststs"] = {}
  7653. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7654. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7655. App.log.debug("Checking for updates @ %s" % full_url)
  7656. # ## Get the data
  7657. try:
  7658. f = urllib.request.urlopen(full_url)
  7659. except Exception:
  7660. # App.log.warning("Failed checking for latest version. Could not connect.")
  7661. self.log.warning("Failed checking for latest version. Could not connect.")
  7662. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7663. return
  7664. try:
  7665. data = json.load(f)
  7666. except Exception as e:
  7667. App.log.error("Could not parse information about latest version.")
  7668. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7669. App.log.debug("json.load(): %s" % str(e))
  7670. f.close()
  7671. return
  7672. f.close()
  7673. # ## Latest version?
  7674. if self.version >= data["version"]:
  7675. App.log.debug("FlatCAM is up to date!")
  7676. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7677. return
  7678. App.log.debug("Newer version available.")
  7679. self.message.emit(
  7680. _("Newer Version Available"),
  7681. '%s<br><br>><b>%s</b><br>%s' % (
  7682. _("There is a newer version of FlatCAM available for download:"),
  7683. str(data["name"]),
  7684. str(data["message"])
  7685. ),
  7686. _("info")
  7687. )
  7688. def on_plotcanvas_setup(self, container=None):
  7689. """
  7690. This is doing the setup for the plot area (canvas).
  7691. :param container: QT Widget where to install the canvas
  7692. :return: None
  7693. """
  7694. if container:
  7695. plot_container = container
  7696. else:
  7697. plot_container = self.ui.right_layout
  7698. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7699. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7700. self.is_legacy = True
  7701. self.defaults["global_graphic_engine"] = "2D"
  7702. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7703. else:
  7704. try:
  7705. self.plotcanvas = PlotCanvas(plot_container, self)
  7706. except Exception as er:
  7707. msg_txt = traceback.format_exc()
  7708. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7709. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7710. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7711. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7712. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7713. msg += msg_txt
  7714. self.inform.emit(msg)
  7715. return 'fail'
  7716. # So it can receive key presses
  7717. self.plotcanvas.native.setFocus()
  7718. if self.is_legacy is False:
  7719. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7720. # Set the mouse button for panning
  7721. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7722. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7723. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7724. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7725. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7726. # Keys over plot enabled
  7727. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7728. if self.defaults['global_cursor_type'] == 'small':
  7729. self.app_cursor = self.plotcanvas.new_cursor()
  7730. else:
  7731. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7732. if self.ui.grid_snap_btn.isChecked():
  7733. self.app_cursor.enabled = True
  7734. else:
  7735. self.app_cursor.enabled = False
  7736. if self.is_legacy is False:
  7737. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7738. else:
  7739. # will use the default Matplotlib axes
  7740. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7741. def on_zoom_fit(self):
  7742. """
  7743. Callback for zoom-fit request. This can be either from the corresponding
  7744. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7745. with axes limits from the geometry bounds of all objects.
  7746. :return: None
  7747. """
  7748. if self.is_legacy is False:
  7749. self.plotcanvas.fit_view()
  7750. else:
  7751. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7752. width = xmax - xmin
  7753. height = ymax - ymin
  7754. xmin -= 0.05 * width
  7755. xmax += 0.05 * width
  7756. ymin -= 0.05 * height
  7757. ymax += 0.05 * height
  7758. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7759. def on_zoom_in(self):
  7760. """
  7761. Callback for zoom-in request.
  7762. :return:
  7763. """
  7764. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7765. def on_zoom_out(self):
  7766. """
  7767. Callback for zoom-out request.
  7768. :return:
  7769. """
  7770. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7771. def disable_all_plots(self):
  7772. self.defaults.report_usage("disable_all_plots()")
  7773. self.disable_plots(self.collection.get_list())
  7774. self.inform.emit('[success] %s' %
  7775. _("All plots disabled."))
  7776. def disable_other_plots(self):
  7777. self.defaults.report_usage("disable_other_plots()")
  7778. self.disable_plots(self.collection.get_non_selected())
  7779. self.inform.emit('[success] %s' %
  7780. _("All non selected plots disabled."))
  7781. def enable_all_plots(self):
  7782. self.defaults.report_usage("enable_all_plots()")
  7783. self.enable_plots(self.collection.get_list())
  7784. self.inform.emit('[success] %s' %
  7785. _("All plots enabled."))
  7786. def on_enable_sel_plots(self):
  7787. log.debug("App.on_enable_sel_plot()")
  7788. object_list = self.collection.get_selected()
  7789. self.enable_plots(objects=object_list)
  7790. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7791. def on_disable_sel_plots(self):
  7792. log.debug("App.on_disable_sel_plot()")
  7793. # self.inform.emit(_("Disabling plots ..."))
  7794. object_list = self.collection.get_selected()
  7795. self.disable_plots(objects=object_list)
  7796. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7797. def enable_plots(self, objects):
  7798. """
  7799. Enable plots
  7800. :param objects: list of Objects to be enabled
  7801. :return:
  7802. """
  7803. log.debug("Enabling plots ...")
  7804. # self.inform.emit(_("Working ..."))
  7805. for obj in objects:
  7806. if obj.options['plot'] is False:
  7807. obj.options.set_change_callback(lambda x: None)
  7808. obj.options['plot'] = True
  7809. try:
  7810. # only the Gerber obj has on_plot_cb_click() method
  7811. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7812. # disable this cb while disconnected,
  7813. # in case the operation takes time the user is not allowed to change it
  7814. obj.ui.plot_cb.setDisabled(True)
  7815. except AttributeError:
  7816. pass
  7817. obj.set_form_item("plot")
  7818. try:
  7819. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7820. obj.ui.plot_cb.setDisabled(False)
  7821. except AttributeError:
  7822. pass
  7823. obj.options.set_change_callback(obj.on_options_change)
  7824. def worker_task(objs):
  7825. with self.proc_container.new(_("Enabling plots ...")):
  7826. for plot_obj in objs:
  7827. # obj.options['plot'] = True
  7828. if isinstance(plot_obj, CNCJobObject):
  7829. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7830. else:
  7831. plot_obj.plot(visible=True)
  7832. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7833. def disable_plots(self, objects):
  7834. """
  7835. Disables plots
  7836. :param objects: list of Objects to be disabled
  7837. :return:
  7838. """
  7839. # if no objects selected then do nothing
  7840. if not self.collection.get_selected():
  7841. return
  7842. log.debug("Disabling plots ...")
  7843. # self.inform.emit(_("Working ..."))
  7844. for obj in objects:
  7845. if obj.options['plot'] is True:
  7846. obj.options.set_change_callback(lambda x: None)
  7847. obj.options['plot'] = False
  7848. try:
  7849. # only the Gerber obj has on_plot_cb_click() method
  7850. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7851. obj.ui.plot_cb.setDisabled(True)
  7852. except AttributeError:
  7853. pass
  7854. obj.set_form_item("plot")
  7855. try:
  7856. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7857. obj.ui.plot_cb.setDisabled(False)
  7858. except AttributeError:
  7859. pass
  7860. obj.options.set_change_callback(obj.on_options_change)
  7861. try:
  7862. self.delete_selection_shape()
  7863. except Exception as e:
  7864. log.debug("App.disable_plots() --> %s" % str(e))
  7865. def worker_task(objs):
  7866. with self.proc_container.new(_("Disabling plots ...")):
  7867. for plot_obj in objs:
  7868. # obj.options['plot'] = True
  7869. if isinstance(plot_obj, CNCJobObject):
  7870. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7871. else:
  7872. plot_obj.plot(visible=False)
  7873. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7874. def toggle_plots(self, objects):
  7875. """
  7876. Toggle plots visibility
  7877. :param objects: list of Objects for which to be toggled the visibility
  7878. :return: None
  7879. """
  7880. # if no objects selected then do nothing
  7881. if not self.collection.get_selected():
  7882. return
  7883. log.debug("Toggling plots ...")
  7884. self.inform.emit(_("Working ..."))
  7885. for obj in objects:
  7886. if obj.options['plot'] is False:
  7887. obj.options['plot'] = True
  7888. else:
  7889. obj.options['plot'] = False
  7890. self.app_obj.plots_updated.emit()
  7891. def clear_plots(self):
  7892. """
  7893. Clear the plots
  7894. :return: None
  7895. """
  7896. objects = self.collection.get_list()
  7897. for obj in objects:
  7898. obj.clear(obj == objects[-1])
  7899. # Clear pool to free memory
  7900. self.clear_pool()
  7901. def on_set_color_action_triggered(self):
  7902. """
  7903. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7904. :return:
  7905. """
  7906. new_color = self.defaults['gerber_plot_fill']
  7907. clicked_action = self.sender()
  7908. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7909. act_name = clicked_action.text()
  7910. sel_obj_list = self.collection.get_selected()
  7911. if not sel_obj_list:
  7912. return
  7913. # a default value, I just chose this one
  7914. alpha_level = 'BF'
  7915. for sel_obj in sel_obj_list:
  7916. if sel_obj.kind == 'excellon':
  7917. alpha_level = str(hex(
  7918. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7919. elif sel_obj.kind == 'gerber':
  7920. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7921. elif sel_obj.kind == 'geometry':
  7922. alpha_level = 'FF'
  7923. else:
  7924. log.debug(
  7925. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7926. continue
  7927. sel_obj.alpha_level = alpha_level
  7928. if act_name == _('Red'):
  7929. new_color = '#FF0000' + alpha_level
  7930. if act_name == _('Blue'):
  7931. new_color = '#0000FF' + alpha_level
  7932. if act_name == _('Yellow'):
  7933. new_color = '#FFDF00' + alpha_level
  7934. if act_name == _('Green'):
  7935. new_color = '#00FF00' + alpha_level
  7936. if act_name == _('Purple'):
  7937. new_color = '#FF00FF' + alpha_level
  7938. if act_name == _('Brown'):
  7939. new_color = '#A52A2A' + alpha_level
  7940. if act_name == _('White'):
  7941. new_color = '#FFFFFF' + alpha_level
  7942. if act_name == _('Black'):
  7943. new_color = '#000000' + alpha_level
  7944. if act_name == _('Custom'):
  7945. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7946. c_dialog = QtWidgets.QColorDialog()
  7947. plot_fill_color = c_dialog.getColor(initial=new_color)
  7948. if plot_fill_color.isValid() is False:
  7949. return
  7950. new_color = str(plot_fill_color.name()) + alpha_level
  7951. if act_name == _("Default"):
  7952. for sel_obj in sel_obj_list:
  7953. if sel_obj.kind == 'excellon':
  7954. new_color = self.defaults['excellon_plot_fill']
  7955. new_line_color = self.defaults['excellon_plot_line']
  7956. elif sel_obj.kind == 'gerber':
  7957. new_color = self.defaults['gerber_plot_fill']
  7958. new_line_color = self.defaults['gerber_plot_line']
  7959. elif sel_obj.kind == 'geometry':
  7960. new_color = self.defaults['geometry_plot_line']
  7961. new_line_color = self.defaults['geometry_plot_line']
  7962. else:
  7963. log.debug(
  7964. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7965. continue
  7966. sel_obj.fill_color = new_color
  7967. sel_obj.outline_color = new_line_color
  7968. sel_obj.shapes.redraw(
  7969. update_colors=(new_color, new_line_color)
  7970. )
  7971. return
  7972. if act_name == _("Opacity"):
  7973. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7974. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7975. if ok_button:
  7976. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7977. for sel_obj in sel_obj_list:
  7978. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7979. sel_obj.shapes.redraw(
  7980. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7981. )
  7982. return
  7983. new_line_color = color_variant(new_color[:7], 0.7)
  7984. if act_name == _("White"):
  7985. new_line_color = color_variant("#dedede", 0.7)
  7986. for sel_obj in sel_obj_list:
  7987. sel_obj.fill_color = new_color
  7988. sel_obj.outline_color = new_line_color
  7989. sel_obj.shapes.redraw(
  7990. update_colors=(new_color, new_line_color)
  7991. )
  7992. def generate_cnc_job(self, objects):
  7993. """
  7994. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7995. :param objects: Selected objects in the Project Tab
  7996. :return:
  7997. """
  7998. self.defaults.report_usage("generate_cnc_job()")
  7999. # for obj in objects:
  8000. # obj.generatecncjob()
  8001. for obj in objects:
  8002. obj.on_generatecnc_button_click()
  8003. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8004. """
  8005. Saves the current project to the specified file.
  8006. :param filename: Name of the file in which to save.
  8007. :type filename: str
  8008. :param quit_action: if the project saving will be followed by an app quit; boolean
  8009. :param silent: if True will not display status messages
  8010. :param from_tcl True is run from Tcl Shell
  8011. :return: None
  8012. """
  8013. self.log.debug("save_project()")
  8014. self.save_in_progress = True
  8015. with self.proc_container.new(_("Saving FlatCAM Project")):
  8016. # Capture the latest changes
  8017. # Current object
  8018. try:
  8019. current_object = self.collection.get_active()
  8020. if current_object:
  8021. current_object.read_form()
  8022. except Exception as e:
  8023. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8024. pass
  8025. # Serialize the whole project
  8026. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8027. "options": self.options,
  8028. "version": self.version}
  8029. if self.defaults["global_save_compressed"] is True:
  8030. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8031. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8032. # # Write
  8033. f.write(g)
  8034. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8035. else:
  8036. # Open file
  8037. try:
  8038. f = open(filename, 'w')
  8039. except IOError:
  8040. App.log.error("Failed to open file for saving: %s", filename)
  8041. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8042. return
  8043. # Write
  8044. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8045. f.close()
  8046. # verification of the saved project
  8047. # Open and parse
  8048. try:
  8049. saved_f = open(filename, 'r')
  8050. except IOError:
  8051. if silent is False:
  8052. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8053. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8054. return
  8055. try:
  8056. saved_d = json.load(saved_f, object_hook=dict2obj)
  8057. except Exception:
  8058. if silent is False:
  8059. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8060. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8061. f.close()
  8062. return
  8063. saved_f.close()
  8064. if silent is False:
  8065. if 'version' in saved_d:
  8066. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8067. else:
  8068. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8069. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8070. tb_settings = QSettings("Open Source", "FlatCAM")
  8071. lock_state = self.ui.lock_action.isChecked()
  8072. tb_settings.setValue('toolbar_lock', lock_state)
  8073. # This will write the setting to the platform specific storage.
  8074. del tb_settings
  8075. # if quit:
  8076. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8077. # t.start()
  8078. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8079. def start_delayed_quit(self, delay, filename, should_quit=None):
  8080. """
  8081. :param delay: period of checking if project file size is more than zero; in seconds
  8082. :param filename: the name of the project file to be checked periodically for size more than zero
  8083. :param should_quit: if the task finished will be followed by an app quit; boolean
  8084. :return:
  8085. """
  8086. to_quit = should_quit
  8087. self.save_timer = QtCore.QTimer()
  8088. self.save_timer.setInterval(delay)
  8089. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8090. self.save_timer.start()
  8091. def check_project_file_size(self, filename, should_quit=None):
  8092. """
  8093. :param filename: the name of the project file to be checked periodically for size more than zero
  8094. :param should_quit: will quit the app if True; boolean
  8095. :return:
  8096. """
  8097. try:
  8098. if os.stat(filename).st_size > 0:
  8099. self.save_in_progress = False
  8100. self.save_timer.stop()
  8101. if should_quit:
  8102. self.app_quit.emit()
  8103. except Exception:
  8104. traceback.print_exc()
  8105. def save_project_auto(self):
  8106. """
  8107. Called periodically to save the project.
  8108. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8109. # progress.
  8110. :return:
  8111. """
  8112. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8113. self.on_file_saveproject()
  8114. def save_project_auto_update(self):
  8115. """
  8116. Update the auto save time interval value.
  8117. :return:
  8118. """
  8119. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8120. try:
  8121. if self.autosave_timer.isActive():
  8122. self.autosave_timer.stop()
  8123. except Exception:
  8124. pass
  8125. if self.defaults['global_autosave'] is True:
  8126. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8127. self.autosave_timer.start()
  8128. def on_options_app2project(self):
  8129. """
  8130. Callback for Options->Transfer Options->App=>Project. Copies options
  8131. from application defaults to project defaults.
  8132. :return: None
  8133. """
  8134. self.defaults.report_usage("on_options_app2project")
  8135. self.preferencesUiManager.defaults_read_form()
  8136. self.options.update(self.defaults)
  8137. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8138. """
  8139. Shows a message on the FlatCAM Shell
  8140. :param msg: Message to display.
  8141. :param show: Opens the shell.
  8142. :param error: Shows the message as an error.
  8143. :param warning: Shows the message as an warning.
  8144. :param success: Shows the message as an success.
  8145. :param selected: Indicate that something was selected on canvas
  8146. :return: None
  8147. """
  8148. if show:
  8149. self.ui.shell_dock.show()
  8150. try:
  8151. if error:
  8152. self.shell.append_error(msg + "\n")
  8153. elif warning:
  8154. self.shell.append_warning(msg + "\n")
  8155. elif success:
  8156. self.shell.append_success(msg + "\n")
  8157. elif selected:
  8158. self.shell.append_selected(msg + "\n")
  8159. else:
  8160. self.shell.append_output(msg + "\n")
  8161. except AttributeError:
  8162. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8163. class ArgsThread(QtCore.QObject):
  8164. open_signal = pyqtSignal(list)
  8165. start = pyqtSignal()
  8166. stop = pyqtSignal()
  8167. if sys.platform == 'win32':
  8168. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8169. else:
  8170. address = ('/tmp/testipc', 'AF_UNIX')
  8171. def __init__(self):
  8172. super(ArgsThread, self).__init__()
  8173. self.listener = None
  8174. self.thread_exit = False
  8175. self.start.connect(self.run)
  8176. self.stop.connect(self.close_listener)
  8177. def my_loop(self, address):
  8178. try:
  8179. self.listener = Listener(*address)
  8180. while self.thread_exit is False:
  8181. conn = self.listener.accept()
  8182. self.serve(conn)
  8183. except socket.error:
  8184. try:
  8185. conn = Client(*address)
  8186. conn.send(sys.argv)
  8187. conn.send('close')
  8188. # close the current instance only if there are args
  8189. if len(sys.argv) > 1:
  8190. try:
  8191. self.listener.close()
  8192. except Exception:
  8193. pass
  8194. sys.exit()
  8195. except ConnectionRefusedError:
  8196. if sys.platform == 'win32':
  8197. pass
  8198. else:
  8199. os.system('rm /tmp/testipc')
  8200. self.listener = Listener(*address)
  8201. while True:
  8202. conn = self.listener.accept()
  8203. self.serve(conn)
  8204. def serve(self, conn):
  8205. while self.thread_exit is False:
  8206. msg = conn.recv()
  8207. if msg == 'close':
  8208. break
  8209. self.open_signal.emit(msg)
  8210. conn.close()
  8211. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8212. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8213. @pyqtSlot()
  8214. def run(self):
  8215. self.my_loop(self.address)
  8216. @pyqtSlot()
  8217. def close_listener(self):
  8218. self.thread_exit = True
  8219. self.listener.close()
  8220. # end of file