FlatCAMApp.py 484 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904
  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. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from PyQt5.QtCore import pyqtSlot, Qt
  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. # Diverse
  37. from FlatCAMCommon import LoudDict, color_variant, ExclusionAreas
  38. from FlatCAMBookmark import BookmarkManager
  39. from FlatCAMDB import ToolsDB2
  40. from vispy.gloo.util import _screenshot
  41. from vispy.io import write_png
  42. # FlatCAM Objects
  43. from defaults import FlatCAMDefaults
  44. from flatcamGUI.preferences.OptionsGroupUI import OptionsGroupUI
  45. from flatcamGUI.preferences.PreferencesUIManager import PreferencesUIManager
  46. from flatcamObjects.ObjectCollection import *
  47. from flatcamObjects.FlatCAMObj import FlatCAMObj
  48. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  49. from flatcamObjects.FlatCAMDocument import DocumentObject
  50. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  51. from flatcamObjects.FlatCAMGeometry import GeometryObject
  52. from flatcamObjects.FlatCAMGerber import GerberObject
  53. from flatcamObjects.FlatCAMScript import ScriptObject
  54. # FlatCAM Parsing files
  55. from flatcamParsers.ParseExcellon import Excellon
  56. from flatcamParsers.ParseGerber import Gerber
  57. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  58. # FlatCAM GUI
  59. from flatcamGUI.PlotCanvas import *
  60. from flatcamGUI.PlotCanvasLegacy import *
  61. from flatcamGUI.FlatCAMGUI import *
  62. from flatcamGUI.GUIElements import FCFileSaveDialog
  63. # FlatCAM Pre-processors
  64. from FlatCAMPostProc import load_preprocessors
  65. # FlatCAM Editors
  66. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  67. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  68. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  69. from flatcamEditors.FlatCAMTextEditor import TextEditor
  70. from flatcamParsers.ParseHPGL2 import HPGL2
  71. # FlatCAM Workers
  72. from FlatCAMProcess import *
  73. from FlatCAMWorkerStack import WorkerStack
  74. # FlatCAM Tools
  75. from flatcamTools import *
  76. # FlatCAM Translation
  77. import gettext
  78. import FlatCAMTranslation as fcTranslate
  79. import builtins
  80. if sys.platform == 'win32':
  81. import winreg
  82. from win32comext.shell import shell, shellcon
  83. fcTranslate.apply_language('strings')
  84. if '_' not in builtins.__dict__:
  85. _ = gettext.gettext
  86. class App(QtCore.QObject):
  87. """
  88. The main application class. The constructor starts the GUI.
  89. """
  90. # ###############################################################################################################
  91. # ########################################## App ################################################################
  92. # ###############################################################################################################
  93. # ###############################################################################################################
  94. # ######################################### LOGGING #############################################################
  95. # ###############################################################################################################
  96. log = logging.getLogger('base')
  97. log.setLevel(logging.DEBUG)
  98. # log.setLevel(logging.WARNING)
  99. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  100. handler = logging.StreamHandler()
  101. handler.setFormatter(formatter)
  102. log.addHandler(handler)
  103. # ###############################################################################################################
  104. # #################################### Get Cmd Line Options #####################################################
  105. # ###############################################################################################################
  106. cmd_line_shellfile = ''
  107. cmd_line_shellvar = ''
  108. cmd_line_headless = None
  109. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  110. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  111. "FlatCam.py --headless=1"
  112. try:
  113. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  114. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  115. "shellvar=",
  116. "headless=",
  117. "multiprocessing-fork="])
  118. except getopt.GetoptError:
  119. print(cmd_line_help)
  120. sys.exit(2)
  121. for opt, arg in cmd_line_options:
  122. if opt == '-h':
  123. print(cmd_line_help)
  124. sys.exit()
  125. elif opt == '--shellfile':
  126. cmd_line_shellfile = arg
  127. elif opt == '--shellvar':
  128. cmd_line_shellvar = arg
  129. elif opt == '--headless':
  130. try:
  131. cmd_line_headless = eval(arg)
  132. except NameError:
  133. pass
  134. # ###############################################################################################################
  135. # ################################### Version and VERSION DATE ##################################################
  136. # ###############################################################################################################
  137. version = 8.993
  138. version_date = "2020/08/01"
  139. beta = True
  140. engine = '3D'
  141. # current date now
  142. date = str(datetime.today()).rpartition('.')[0]
  143. date = ''.join(c for c in date if c not in ':-')
  144. date = date.replace(' ', '_')
  145. # ###############################################################################################################
  146. # ############################################ URLS's ###########################################################
  147. # ###############################################################################################################
  148. # URL for update checks and statistics
  149. version_url = "http://flatcam.org/version"
  150. # App URL
  151. app_url = "http://flatcam.org"
  152. # Manual URL
  153. manual_url = "http://flatcam.org/manual/index.html"
  154. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  155. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  156. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  157. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  158. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  159. # this variable will hold the project status
  160. # if True it will mean that the project was modified and not saved
  161. should_we_save = False
  162. # flag is True if saving action has been triggered
  163. save_in_progress = False
  164. # ###############################################################################################################
  165. # ####################################### APP Signals ######################################################
  166. # ###############################################################################################################
  167. # Inform the user
  168. # Handled by:
  169. # * App.info() --> Print on the status bar
  170. inform = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. plots_updated = QtCore.pyqtSignal()
  188. # Emitted by new_object() and passes the new object as argument, plot flag.
  189. # on_object_created() adds the object to the collection, plots on appropriate flag
  190. # and emits new_object_available.
  191. object_created = QtCore.pyqtSignal(object, bool, bool)
  192. # Emitted when a object has been changed (like scaled, mirrored)
  193. object_changed = QtCore.pyqtSignal(object)
  194. # Emitted after object has been plotted.
  195. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  196. object_plotted = QtCore.pyqtSignal(object)
  197. # Emitted when a new object has been added or deleted from/to the collection
  198. object_status_changed = QtCore.pyqtSignal(object, str, str)
  199. message = QtCore.pyqtSignal(str, str, str)
  200. # Emmited when shell command is finished(one command only)
  201. shell_command_finished = QtCore.pyqtSignal(object)
  202. # Emitted when multiprocess pool has been recreated
  203. pool_recreated = QtCore.pyqtSignal(object)
  204. # Emitted when an unhandled exception happens
  205. # in the worker task.
  206. thread_exception = QtCore.pyqtSignal(object)
  207. # used to signal that there are arguments for the app
  208. args_at_startup = QtCore.pyqtSignal(list)
  209. # a reusable signal to replot a list of objects
  210. # should be disconnected after use so it can be reused
  211. replot_signal = pyqtSignal(list)
  212. # signal emitted when jumping
  213. jump_signal = pyqtSignal(tuple)
  214. # signal emitted when jumping
  215. locate_signal = pyqtSignal(tuple, str)
  216. # close app signal
  217. close_app_signal = pyqtSignal()
  218. # will perform the cleanup operation after a Graceful Exit
  219. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  220. # graphic residues behind
  221. cleanup = pyqtSignal()
  222. def __init__(self, user_defaults=True):
  223. """
  224. Starts the application.
  225. :return: app
  226. :rtype: App
  227. """
  228. super().__init__()
  229. App.log.info("FlatCAM Starting...")
  230. self.main_thread = QtWidgets.QApplication.instance().thread()
  231. # ############################################################################################################
  232. # ################# Setup the listening thread for another instance launching with args ######################
  233. # ############################################################################################################
  234. if sys.platform == 'win32' or sys.platform == 'linux':
  235. # make sure the thread is stored by using a self. otherwise it's garbage collected
  236. self.th = QtCore.QThread()
  237. self.th.start(priority=QtCore.QThread.LowestPriority)
  238. self.new_launch = ArgsThread()
  239. self.new_launch.open_signal[list].connect(self.on_startup_args)
  240. self.new_launch.moveToThread(self.th)
  241. self.new_launch.start.emit()
  242. # ############################################################################################################
  243. # # ######################################## OS-specific #####################################################
  244. # ############################################################################################################
  245. portable = False
  246. # Folder for user settings.
  247. if sys.platform == 'win32':
  248. if platform.architecture()[0] == '32bit':
  249. App.log.debug("Win32!")
  250. else:
  251. App.log.debug("Win64!")
  252. # #######################################################################################################
  253. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  254. # #######################################################################################################
  255. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  256. try:
  257. with open(config_file, 'r'):
  258. pass
  259. except FileNotFoundError:
  260. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  261. try:
  262. with open(config_file, 'r') as f:
  263. try:
  264. for line in f:
  265. param = str(line).replace('\n', '').rpartition('=')
  266. if param[0] == 'portable':
  267. try:
  268. portable = eval(param[2])
  269. except NameError:
  270. portable = False
  271. if param[0] == 'headless':
  272. if param[2].lower() == 'true':
  273. self.cmd_line_headless = 1
  274. else:
  275. self.cmd_line_headless = None
  276. except Exception as e:
  277. log.debug('App.__init__() -->%s' % str(e))
  278. return
  279. except FileNotFoundError as e:
  280. log.debug(str(e))
  281. pass
  282. if portable is False:
  283. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  284. else:
  285. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  286. self.os = 'windows'
  287. else: # Linux/Unix/MacOS
  288. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  289. self.os = 'unix'
  290. # ############################################################################################################
  291. # ################################# Setup folders and files ##################################################
  292. # ############################################################################################################
  293. if not os.path.exists(self.data_path):
  294. os.makedirs(self.data_path)
  295. App.log.debug('Created data folder: ' + self.data_path)
  296. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  297. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  298. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  299. if not os.path.exists(self.preprocessorpaths):
  300. os.makedirs(self.preprocessorpaths)
  301. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  302. # create geo_tools_db.FlatDB file if there is none
  303. try:
  304. f = open(self.data_path + '/geo_tools_db.FlatDB')
  305. f.close()
  306. except IOError:
  307. App.log.debug('Creating empty geo_tool_db.FlatDB')
  308. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  309. json.dump({}, f)
  310. f.close()
  311. # create current_defaults.FlatConfig file if there is none
  312. try:
  313. f = open(self.data_path + '/current_defaults.FlatConfig')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty current_defaults.FlatConfig')
  317. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  318. json.dump({}, f)
  319. f.close()
  320. # Write factory_defaults.FlatConfig file to disk
  321. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  322. # create a recent files json file if there is none
  323. try:
  324. f = open(self.data_path + '/recent.json')
  325. f.close()
  326. except IOError:
  327. App.log.debug('Creating empty recent.json')
  328. f = open(self.data_path + '/recent.json', 'w')
  329. json.dump([], f)
  330. f.close()
  331. # create a recent projects json file if there is none
  332. try:
  333. fp = open(self.data_path + '/recent_projects.json')
  334. fp.close()
  335. except IOError:
  336. App.log.debug('Creating empty recent_projects.json')
  337. fp = open(self.data_path + '/recent_projects.json', 'w')
  338. json.dump([], fp)
  339. fp.close()
  340. # Application directory. CHDIR to it. Otherwise, trying to load
  341. # GUI icons will fail as their path is relative.
  342. # This will fail under cx_freeze ...
  343. self.app_home = os.path.dirname(os.path.realpath(__file__))
  344. App.log.debug("Application path is " + self.app_home)
  345. App.log.debug("Started in " + os.getcwd())
  346. # cx_freeze workaround
  347. if os.path.isfile(self.app_home):
  348. self.app_home = os.path.dirname(self.app_home)
  349. os.chdir(self.app_home)
  350. # ############################################################################################################
  351. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  352. # ############################################################################################################
  353. self.defaults = FlatCAMDefaults()
  354. self.defaults["root_folder_path"] = self.app_home
  355. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  356. if user_defaults:
  357. self.defaults.load(filename=current_defaults_path)
  358. if self.defaults['units'] == 'MM':
  359. self.decimals = int(self.defaults['decimals_metric'])
  360. else:
  361. self.decimals = int(self.defaults['decimals_inch'])
  362. if self.defaults["global_gray_icons"] is False:
  363. self.resource_location = 'assets/resources'
  364. else:
  365. self.resource_location = 'assets/resources/dark_resources'
  366. self.current_units = self.defaults['units']
  367. # ###########################################################################################################
  368. # #################################### SETUP OBJECT CLASSES #################################################
  369. # ###########################################################################################################
  370. self.setup_obj_classes()
  371. # ###########################################################################################################
  372. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  373. # ###########################################################################################################
  374. self.pool = Pool()
  375. # ###########################################################################################################
  376. # ###################################### Setting the Splash Screen ##########################################
  377. # ###########################################################################################################
  378. splash_settings = QSettings("Open Source", "FlatCAM")
  379. if splash_settings.contains("splash_screen"):
  380. show_splash = splash_settings.value("splash_screen")
  381. else:
  382. splash_settings.setValue('splash_screen', 1)
  383. # This will write the setting to the platform specific storage.
  384. del splash_settings
  385. show_splash = 1
  386. if show_splash and self.cmd_line_headless != 1:
  387. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  388. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  389. # self.splash.setMask(splash_pix.mask())
  390. # move splashscreen to the current monitor
  391. desktop = QtWidgets.QApplication.desktop()
  392. screen = desktop.screenNumber(QtGui.QCursor.pos())
  393. current_screen_center = desktop.availableGeometry(screen).center()
  394. self.splash.move(current_screen_center - self.splash.rect().center())
  395. self.splash.show()
  396. self.splash.showMessage(_("FlatCAM is initializing ..."),
  397. alignment=Qt.AlignBottom | Qt.AlignLeft,
  398. color=QtGui.QColor("gray"))
  399. else:
  400. show_splash = 0
  401. # ###########################################################################################################
  402. # ######################################### Initialize GUI ##################################################
  403. # ###########################################################################################################
  404. # FlatCAM colors used in plotting
  405. self.FC_light_green = '#BBF268BF'
  406. self.FC_dark_green = '#006E20BF'
  407. self.FC_light_blue = '#a5a5ffbf'
  408. self.FC_dark_blue = '#0000ffbf'
  409. self.ui = FlatCAMGUI(self)
  410. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  411. if theme_settings.contains("theme"):
  412. theme = theme_settings.value('theme', type=str)
  413. else:
  414. theme = 'white'
  415. if self.defaults["global_cursor_color_enabled"]:
  416. self.cursor_color_3D = self.defaults["global_cursor_color"]
  417. else:
  418. if theme == 'white':
  419. self.cursor_color_3D = 'black'
  420. else:
  421. self.cursor_color_3D = 'gray'
  422. # update the defaults dict with the setting in QSetting
  423. self.defaults['global_theme'] = theme
  424. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  425. self.ui.final_save.connect(self.final_save)
  426. # restore the toolbar view
  427. self.restore_toolbar_view()
  428. # restore the GUI geometry
  429. self.restore_main_win_geom()
  430. # set FlatCAM units in the Status bar
  431. self.set_screen_units(self.defaults['units'])
  432. # ###########################################################################################################
  433. # ########################################### AUTOSAVE SETUP ################################################
  434. # ###########################################################################################################
  435. self.block_autosave = False
  436. self.autosave_timer = QtCore.QTimer(self)
  437. self.save_project_auto_update()
  438. self.autosave_timer.timeout.connect(self.save_project_auto)
  439. # ###########################################################################################################
  440. # #################################### LOAD PREPROCESSORS ###################################################
  441. # ###########################################################################################################
  442. # ----------------------------------------- WARNING --------------------------------------------------------
  443. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  444. # That's because the number of preprocessors can vary and here the comboboxes are populated
  445. # -----------------------------------------------------------------------------------------------------------
  446. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  447. # the preprocessor file
  448. self.preprocessors = load_preprocessors(self)
  449. # make sure that always the 'default' preprocessor is the first item in the dictionary
  450. if 'default' in self.preprocessors.keys():
  451. new_ppp_dict = {}
  452. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  453. default_pp = self.preprocessors.pop('default')
  454. new_ppp_dict['default'] = default_pp
  455. # then add the rest of the keys
  456. for name, val_class in self.preprocessors.items():
  457. new_ppp_dict[name] = val_class
  458. # and now put back the ordered dict with 'default' key first
  459. self.preprocessors = new_ppp_dict
  460. for name in list(self.preprocessors.keys()):
  461. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  462. if name.partition('_')[0] == 'Paste':
  463. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  464. continue
  465. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  466. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  467. if name == 'hpgl':
  468. continue
  469. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  470. # ###########################################################################################################
  471. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  472. # ###########################################################################################################
  473. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  474. inform=self.inform)
  475. self.preferencesUiManager.defaults_write_form()
  476. # When the self.defaults dictionary changes will update the Preferences GUI forms
  477. self.defaults.set_change_callback(self.on_defaults_dict_change)
  478. # ###########################################################################################################
  479. # ##################################### FIRST RUN SECTION ###################################################
  480. # ################################ It's done only once after install #####################################
  481. # ###########################################################################################################
  482. if self.defaults["first_run"] is True:
  483. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  484. initial_lay = 'minimal'
  485. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  486. # Set the combobox in Preferences to the current layout
  487. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  488. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  489. # after the first run, this object should be False
  490. self.defaults["first_run"] = False
  491. self.preferencesUiManager.save_defaults(silent=True)
  492. # ###########################################################################################################
  493. # ############################################ Data #########################################################
  494. # ###########################################################################################################
  495. self.recent = []
  496. self.recent_projects = []
  497. self.clipboard = QtWidgets.QApplication.clipboard()
  498. self.project_filename = None
  499. self.toggle_units_ignore = False
  500. # ###########################################################################################################
  501. # ########################################## LOAD LANGUAGES ################################################
  502. # ###########################################################################################################
  503. self.languages = fcTranslate.load_languages()
  504. for name in sorted(self.languages.values()):
  505. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  506. # ###########################################################################################################
  507. # ####################################### APPLY APP LANGUAGE ################################################
  508. # ###########################################################################################################
  509. ret_val = fcTranslate.apply_language('strings')
  510. if ret_val == "no language":
  511. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  512. log.debug("Could not find the Language files. The App strings are missing.")
  513. else:
  514. # make the current language the current selection on the language combobox
  515. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  516. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  517. # ###########################################################################################################
  518. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  519. # ###########################################################################################################
  520. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  521. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  522. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  523. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  524. self.defaults.propagate_defaults()
  525. # ###########################################################################################################
  526. # ######################################## UPDATE THE OPTIONS ###############################################
  527. # ###########################################################################################################
  528. self.options = LoudDict()
  529. # -----------------------------------------------------------------------------------------------------------
  530. # Update the self.options from the self.defaults
  531. # The self.defaults holds the application defaults while the self.options holds the object defaults
  532. # -----------------------------------------------------------------------------------------------------------
  533. # Copy app defaults to project options
  534. for def_key, def_val in self.defaults.items():
  535. self.options[def_key] = deepcopy(def_val)
  536. self.preferencesUiManager.show_preferences_gui()
  537. # ### End of Data ####
  538. # ###########################################################################################################
  539. # #################################### SETUP OBJECT COLLECTION ##############################################
  540. # ###########################################################################################################
  541. self.collection = ObjectCollection(self)
  542. self.ui.project_tab_layout.addWidget(self.collection.view)
  543. # ### Adjust tabs width ## ##
  544. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  545. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  546. self.collection.view.setMinimumWidth(290)
  547. self.log.debug("Finished creating Object Collection.")
  548. # ###########################################################################################################
  549. # ######################################## SETUP Plot Area ##################################################
  550. # ###########################################################################################################
  551. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  552. if self.defaults["global_graphic_engine"] == '3D':
  553. self.is_legacy = False
  554. else:
  555. self.is_legacy = True
  556. # Event signals disconnect id holders
  557. self.mp = None
  558. self.mm = None
  559. self.mr = None
  560. self.mdc = None
  561. self.mp_zc = None
  562. self.kp = None
  563. # Matplotlib axis
  564. self.axes = None
  565. if show_splash:
  566. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  567. "Canvas initialization started."),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. start_plot_time = time.time() # debug
  571. self.plotcanvas = None
  572. self.app_cursor = None
  573. self.hover_shapes = None
  574. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  575. # setup the PlotCanvas
  576. self.on_plotcanvas_setup()
  577. end_plot_time = time.time()
  578. self.used_time = end_plot_time - start_plot_time
  579. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  580. if show_splash:
  581. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  582. "Canvas initialization started.\n"
  583. "Canvas initialization finished in"), '%.2f' % self.used_time),
  584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  585. color=QtGui.QColor("gray"))
  586. self.ui.splitter.setStretchFactor(1, 2)
  587. # ###########################################################################################################
  588. # ############################################### SYS TRAY ##################################################
  589. # ###########################################################################################################
  590. if self.defaults["global_systray_icon"]:
  591. self.parent_w = QtWidgets.QWidget()
  592. if self.cmd_line_headless == 1:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. headless=True,
  597. parent=self.parent_w)
  598. else:
  599. self.trayIcon = FlatCAMSystemTray(app=self,
  600. icon=QtGui.QIcon(self.resource_location +
  601. '/flatcam_icon32_green.png'),
  602. parent=self.parent_w)
  603. # ###########################################################################################################
  604. # ############################################### Worker SETUP ##############################################
  605. # ###########################################################################################################
  606. if self.defaults["global_worker_number"]:
  607. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  608. else:
  609. self.workers = WorkerStack(workers_number=2)
  610. self.worker_task.connect(self.workers.add_task)
  611. self.log.debug("Finished creating Workers crew.")
  612. # ###########################################################################################################
  613. # ############################################# Activity Monitor ###########################################
  614. # ###########################################################################################################
  615. self.activity_view = FlatCAMActivityView(app=self)
  616. self.ui.infobar.addWidget(self.activity_view)
  617. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  618. # ###########################################################################################################
  619. # ############################################# Signal handling #############################################
  620. # ###########################################################################################################
  621. # ########################################## Custom signals ################################################
  622. # signal for displaying messages in status bar
  623. self.inform.connect(self.info)
  624. # signal to be called when the app is quiting
  625. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  626. self.message.connect(self.message_dialog)
  627. # self.progress.connect(self.set_progress_bar)
  628. # signals that are emitted when object state changes
  629. self.object_created.connect(self.on_object_created)
  630. self.object_changed.connect(self.on_object_changed)
  631. self.object_plotted.connect(self.on_object_plotted)
  632. self.plots_updated.connect(self.on_plots_updated)
  633. # signals emitted when file state change
  634. self.file_opened.connect(self.register_recent)
  635. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  636. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  637. # ########################################## Standard signals ###############################################
  638. # ### Menu
  639. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  640. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  641. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  642. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  643. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  644. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  645. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  646. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  647. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  648. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  649. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  650. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  651. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  652. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  653. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  654. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  655. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  656. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  657. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  658. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  659. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  660. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  661. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  662. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  663. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  664. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  665. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  666. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  667. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  668. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  669. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  670. self.ui.menufile_exit.triggered.connect(self.final_save)
  671. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  672. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  673. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  674. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  675. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  676. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  677. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  678. self.ui.menueditdelete.triggered.connect(self.on_delete)
  679. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  680. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  681. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  682. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  683. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  684. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  685. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  686. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  687. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  688. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  689. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  690. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  691. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  692. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  693. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  694. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  695. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  696. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  697. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  698. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  699. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  700. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  701. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  702. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  703. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  704. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  705. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  706. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  707. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  708. self.ui.menuview_replot.triggered.connect(self.plot_all)
  709. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  710. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  711. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  712. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  713. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  714. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  715. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  716. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  717. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  718. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  719. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  720. self.ui.menuhelp_about.triggered.connect(self.on_about)
  721. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  722. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  723. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  724. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  725. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  726. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  727. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  728. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  729. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  730. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  731. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  732. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  733. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  734. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  735. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  736. # ToolBar signals
  737. self.connect_toolbar_signals()
  738. # Notebook and Plot Tab Area signals
  739. # make the right click on the notebook tab and plot tab area tab raise a menu
  740. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  741. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  742. self.on_tab_setup_context_menu()
  743. # activate initial state
  744. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  745. # Context Menu
  746. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  747. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  748. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  749. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  750. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  751. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  752. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  753. self.ui.clearplot.triggered.connect(self.clear_plots)
  754. self.ui.replot.triggered.connect(self.plot_all)
  755. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  756. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  757. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  758. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  759. self.ui.popmenu_move.triggered.connect(self.obj_move)
  760. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  761. # Project Context Menu -> Color Setting
  762. for act in self.ui.menuprojectcolor.actions():
  763. act.triggered.connect(self.on_set_color_action_triggered)
  764. # ###########################################################################################################
  765. # #################################### GUI PREFERENCES SIGNALS ##############################################
  766. # ###########################################################################################################
  767. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  768. lambda: self.on_toggle_units(no_pref=False))
  769. # ##################################### Workspace Setting Signals ###########################################
  770. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  771. self.on_workspace_modified)
  772. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  773. self.on_workspace_modified
  774. )
  775. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  776. # ###########################################################################################################
  777. # ######################################## GUI SETTINGS SIGNALS #############################################
  778. # ###########################################################################################################
  779. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  780. # ######################################## Tools related signals ############################################
  781. # Film Tool
  782. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  783. self.on_film_color_entry)
  784. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  785. self.on_film_color_button)
  786. # QRCode Tool
  787. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  788. self.on_qrcode_fill_color_entry)
  789. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  790. self.on_qrcode_fill_color_button)
  791. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  792. self.on_qrcode_back_color_entry)
  793. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  794. self.on_qrcode_back_color_button)
  795. # portability changed signal
  796. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  797. # Object list
  798. self.collection.view.activated.connect(self.on_row_activated)
  799. self.collection.item_selected.connect(self.on_row_selected)
  800. self.object_status_changed.connect(self.on_collection_updated)
  801. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  802. # Export Excellon parameters.
  803. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  804. self.on_update_exc_export
  805. )
  806. # call it once to make sure it is updated at startup
  807. self.on_update_exc_export(state=self.defaults["excellon_update"])
  808. # when there are arguments at application startup this get launched
  809. self.args_at_startup[list].connect(self.on_startup_args)
  810. # ###########################################################################################################
  811. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  812. # ###########################################################################################################
  813. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  814. lambda: self.restore_extensions(ext_type='excellon'))
  815. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  816. lambda: self.restore_extensions(ext_type='gcode'))
  817. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  818. lambda: self.restore_extensions(ext_type='gerber'))
  819. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  820. lambda: self.delete_all_extensions(ext_type='excellon'))
  821. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  822. lambda: self.delete_all_extensions(ext_type='gcode'))
  823. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  824. lambda: self.delete_all_extensions(ext_type='gerber'))
  825. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  826. lambda: self.add_extension(ext_type='excellon'))
  827. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  828. lambda: self.add_extension(ext_type='gcode'))
  829. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  830. lambda: self.add_extension(ext_type='gerber'))
  831. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  832. lambda: self.del_extension(ext_type='excellon'))
  833. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  834. lambda: self.del_extension(ext_type='gcode'))
  835. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  836. lambda: self.del_extension(ext_type='gerber'))
  837. # connect the 'Apply' buttons from the Preferences/File Associations
  838. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  839. lambda: self.on_register_files(obj_type='excellon'))
  840. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  841. lambda: self.on_register_files(obj_type='gcode'))
  842. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  843. lambda: self.on_register_files(obj_type='gerber'))
  844. # ###########################################################################################################
  845. # ########################################### KEYWORDS SIGNALS ##############################################
  846. # ###########################################################################################################
  847. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  848. lambda: self.restore_extensions(ext_type='keyword'))
  849. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  850. lambda: self.delete_all_extensions(ext_type='keyword'))
  851. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  852. lambda: self.add_extension(ext_type='keyword'))
  853. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  854. lambda: self.del_extension(ext_type='keyword'))
  855. # connect the abort_all_tasks related slots to the related signals
  856. self.proc_container.idle_flag.connect(self.app_is_idle)
  857. # signal emitted when a tab is closed in the Plot Area
  858. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  859. # signal to close the application
  860. self.close_app_signal.connect(self.kill_app)
  861. # ################################# FINISHED CONNECTING SIGNALS #############################################
  862. # ###########################################################################################################
  863. # ###########################################################################################################
  864. # ###########################################################################################################
  865. self.log.debug("Finished connecting Signals.")
  866. # ###########################################################################################################
  867. # ########################################## Other setups ###################################################
  868. # ###########################################################################################################
  869. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  870. # depending on from where those tools are called different actions can be done
  871. self.call_source = 'app'
  872. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  873. self.tool_tab_locked = False
  874. # decide if to show or hide the Notebook side of the screen at startup
  875. if self.defaults["global_project_at_startup"] is True:
  876. self.ui.splitter.setSizes([1, 1])
  877. else:
  878. self.ui.splitter.setSizes([0, 1])
  879. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  880. self.setup_component_editor()
  881. # ###########################################################################################################
  882. # ####################################### Auto-complete KEYWORDS ############################################
  883. # ###########################################################################################################
  884. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  885. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  886. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  887. 'export_exc',
  888. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  889. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  890. 'interiors', 'isolate', 'join_excellon',
  891. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  892. 'mirror', 'ncc',
  893. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  894. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  895. 'options', 'origin',
  896. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  897. 'save', 'save_project',
  898. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  899. 'skew', 'subtract_poly', 'subtract_rectangle',
  900. 'version', 'write_gcode'
  901. ]
  902. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  903. 'Paste_1',
  904. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  905. 'Toolchange_manual', 'True', 'Users',
  906. 'all', 'auto', 'axis',
  907. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  908. 'contour', 'default',
  909. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  910. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  911. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  912. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  913. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  914. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  915. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  916. 'spacing_columns',
  917. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  918. 'toolchange_xy', 'toolchangez', 'travelz',
  919. 'tooldia', 'use_threads', 'value',
  920. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  921. ]
  922. self.tcl_keywords = [
  923. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  924. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  925. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  926. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  927. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  928. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  929. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  930. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  931. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  932. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  933. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  934. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  935. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  936. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  937. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  938. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  939. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  940. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  941. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  942. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  943. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  944. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  945. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  946. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  947. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  948. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  949. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  950. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  951. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  952. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  953. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  954. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  955. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  956. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  957. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  958. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  959. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  960. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  961. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  962. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  963. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  964. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  965. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  966. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  967. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  968. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  969. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  970. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  971. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  972. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  973. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  974. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  975. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  976. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  977. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  978. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  979. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  980. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  981. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  982. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  983. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  984. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  985. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  986. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  987. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  988. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  989. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  990. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  991. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  992. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  993. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  994. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  995. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  996. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  997. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  998. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  999. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1000. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1001. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1002. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1003. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1004. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1005. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1006. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1007. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1008. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1009. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1010. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1011. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1012. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1013. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1014. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1015. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1016. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1017. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1018. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1019. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1020. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1021. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1022. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1023. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1024. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1025. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1026. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1027. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1028. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1029. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1030. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1031. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1032. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1033. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1034. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1035. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1036. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1037. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1038. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1039. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1040. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1041. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1042. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1043. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1044. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1045. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1046. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1047. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1048. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1049. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1050. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1051. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1052. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1053. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1054. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1055. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1056. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1057. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1058. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1059. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1060. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1061. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1062. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1063. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1064. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1065. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1066. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1067. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1068. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1069. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1070. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1071. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1072. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1073. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1074. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1075. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1076. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1077. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1078. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1079. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1080. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1081. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1082. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1083. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1084. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1085. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1086. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1087. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1088. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1089. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1090. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1091. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1092. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1093. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1094. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1095. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1096. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1097. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1098. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1099. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1100. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1101. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1102. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1103. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1104. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1105. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1106. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1107. ]
  1108. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1109. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1110. # ###########################################################################################################
  1111. # ############################################## Shell SETUP ################################################
  1112. # ###########################################################################################################
  1113. self.shell = FCShell(app=self, version=self.version)
  1114. self.ui.shell_dock.setWidget(self.shell)
  1115. self.log.debug("TCL Shell has been initialized.")
  1116. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1117. if self.defaults["global_shell_at_startup"]:
  1118. self.ui.shell_dock.show()
  1119. else:
  1120. self.ui.shell_dock.hide()
  1121. # ###########################################################################################################
  1122. # ########################################## Tools and Plugins ##############################################
  1123. # ###########################################################################################################
  1124. self.dblsidedtool = None
  1125. self.distance_tool = None
  1126. self.distance_min_tool = None
  1127. self.panelize_tool = None
  1128. self.film_tool = None
  1129. self.paste_tool = None
  1130. self.calculator_tool = None
  1131. self.rules_tool = None
  1132. self.sub_tool = None
  1133. self.move_tool = None
  1134. self.cutout_tool = None
  1135. self.ncclear_tool = None
  1136. self.optimal_tool = None
  1137. self.paint_tool = None
  1138. self.transform_tool = None
  1139. self.properties_tool = None
  1140. self.pdf_tool = None
  1141. self.image_tool = None
  1142. self.pcb_wizard_tool = None
  1143. self.cal_exc_tool = None
  1144. self.qrcode_tool = None
  1145. self.copper_thieving_tool = None
  1146. self.fiducial_tool = None
  1147. self.edrills_tool = None
  1148. self.align_objects_tool = None
  1149. self.punch_tool = None
  1150. self.invert_tool = None
  1151. self.corners_tool = None
  1152. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1153. try:
  1154. self.install_tools()
  1155. except AttributeError as e:
  1156. log.debug("App.__init__() install tools() --> %s" % str(e))
  1157. # ###########################################################################################################
  1158. # ############################################ SETUP RECENT ITEMS ###########################################
  1159. # ###########################################################################################################
  1160. self.setup_recent_items()
  1161. # ###########################################################################################################
  1162. # ######################################### BookMarks Manager ###############################################
  1163. # ###########################################################################################################
  1164. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1165. self.install_bookmarks()
  1166. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1167. # ###########################################################################################################
  1168. # ########################################### Tools Database ################################################
  1169. # ###########################################################################################################
  1170. self.tools_db_tab = None
  1171. # ### System Font Parsing ###
  1172. # self.f_parse = ParseFont(self)
  1173. # self.parse_system_fonts()
  1174. # ###########################################################################################################
  1175. # ######################################### Check for updates ###############################################
  1176. # ###########################################################################################################
  1177. # Separate thread (Not worker)
  1178. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1179. if (self.beta is False or self.beta is None) and \
  1180. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1181. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1182. # self.thr2 = QtCore.QThread()
  1183. self.worker_task.emit({'fcn': self.version_check,
  1184. 'params': []})
  1185. # self.thr2.start(QtCore.QThread.LowPriority)
  1186. # ###########################################################################################################
  1187. # ##################################### Register files with FlatCAM; #######################################
  1188. # ################################### It works only for Windows for now ####################################
  1189. # ###########################################################################################################
  1190. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1191. self.on_register_files()
  1192. # ###########################################################################################################
  1193. # ######################################## Variables for global usage #######################################
  1194. # ###########################################################################################################
  1195. # hold the App units
  1196. self.units = 'MM'
  1197. # coordinates for relative position display
  1198. self.rel_point1 = (0, 0)
  1199. self.rel_point2 = (0, 0)
  1200. # variable to store coordinates
  1201. self.pos = (0, 0)
  1202. self.pos_canvas = (0, 0)
  1203. self.pos_jump = (0, 0)
  1204. # variable to store mouse coordinates
  1205. self.mouse = [0, 0]
  1206. # variable to store the delta positions on cavnas
  1207. self.dx = 0
  1208. self.dy = 0
  1209. # decide if we have a double click or single click
  1210. self.doubleclick = False
  1211. # store here the is_dragging value
  1212. self.event_is_dragging = False
  1213. # variable to store if a command is active (then the var is not None) and which one it is
  1214. self.command_active = None
  1215. # variable to store the status of moving selection action
  1216. # None value means that it's not an selection action
  1217. # True value = a selection from left to right
  1218. # False value = a selection from right to left
  1219. self.selection_type = None
  1220. # List to store the objects that are currently loaded in FlatCAM
  1221. # This list is updated on each object creation or object delete
  1222. self.all_objects_list = []
  1223. self.objects_under_the_click_list = []
  1224. # List to store the objects that are selected
  1225. self.sel_objects_list = []
  1226. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1227. self.key_modifiers = None
  1228. # Variable to hold the status of the axis
  1229. self.toggle_axis = True
  1230. # Variable to hold the status of the grid lines
  1231. self.toggle_grid_lines = True
  1232. # Variable to store the status of the fullscreen event
  1233. self.toggle_fscreen = False
  1234. # Variable to store the status of the code editor
  1235. self.toggle_codeeditor = False
  1236. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1237. self.click_noproject = False
  1238. self.cursor = None
  1239. # Variable to store the GCODE that was edited
  1240. self.gcode_edited = ""
  1241. self.text_editor_tab = None
  1242. # reference for the self.ui.code_editor
  1243. self.reference_code_editor = None
  1244. self.script_code = ''
  1245. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1246. self.tools_db_changed_flag = False
  1247. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1248. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1249. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1250. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1251. 'tsm']
  1252. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1253. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1254. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1255. 'sbp', 'tap', 'xpi']
  1256. self.svg_list = ['svg']
  1257. self.dxf_list = ['dxf']
  1258. self.pdf_list = ['pdf']
  1259. self.prj_list = ['flatprj']
  1260. self.conf_list = ['flatconfig']
  1261. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1262. # flag for polygons not cleared
  1263. self.poly_not_cleared = False
  1264. # VisPy visuals
  1265. self.isHovering = False
  1266. self.notHovering = True
  1267. # Window geometry
  1268. self.x_pos = None
  1269. self.y_pos = None
  1270. self.width = None
  1271. self.height = None
  1272. # when True, the app has to return from any thread
  1273. self.abort_flag = False
  1274. # set the value used in the Windows Title
  1275. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1276. # this holds a widget that is installed in the Plot Area when View Source option is used
  1277. self.source_editor_tab = None
  1278. self.pagesize = {}
  1279. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1280. # VisPy visuals
  1281. if self.is_legacy is False:
  1282. try:
  1283. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1284. except AttributeError:
  1285. self.tool_shapes = None
  1286. else:
  1287. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1288. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1289. # used in the delayed shutdown self.start_delayed_quit() method
  1290. self.save_timer = None
  1291. # ###########################################################################################################
  1292. # ################################## ADDING FlatCAM EDITORS section #########################################
  1293. # ###########################################################################################################
  1294. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1295. # at the first launch of the App , the editors will not be functional.
  1296. try:
  1297. self.geo_editor = FlatCAMGeoEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. try:
  1301. self.exc_editor = FlatCAMExcEditor(self)
  1302. except AttributeError:
  1303. pass
  1304. try:
  1305. self.grb_editor = FlatCAMGrbEditor(self)
  1306. except AttributeError:
  1307. pass
  1308. self.log.debug("Finished adding FlatCAM Editor's.")
  1309. self.set_ui_title(name=_("New Project - Not saved"))
  1310. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1311. current_platform = platform.architecture()[0]
  1312. if current_platform != '64bit':
  1313. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1314. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1315. # ###########################################################################################################
  1316. # ########################################### EXCLUSION AREAS ###############################################
  1317. # ###########################################################################################################
  1318. self.exc_areas = ExclusionAreas(app=self)
  1319. # ###########################################################################################################
  1320. # ##################################### Finished the CONSTRUCTOR ############################################
  1321. # ###########################################################################################################
  1322. App.log.debug("END of constructor. Releasing control.")
  1323. # ###########################################################################################################
  1324. # ########################################## SHOW GUI #######################################################
  1325. # ###########################################################################################################
  1326. # if the app is not started as headless, show it
  1327. if self.cmd_line_headless != 1:
  1328. if show_splash:
  1329. # finish the splash
  1330. self.splash.finish(self.ui)
  1331. mgui_settings = QSettings("Open Source", "FlatCAM")
  1332. if mgui_settings.contains("maximized_gui"):
  1333. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1334. if maximized_ui is True:
  1335. self.ui.showMaximized()
  1336. else:
  1337. self.ui.show()
  1338. else:
  1339. self.ui.show()
  1340. if self.defaults["global_systray_icon"]:
  1341. self.trayIcon.show()
  1342. else:
  1343. log.warning("******************* RUNNING HEADLESS *******************")
  1344. # ###########################################################################################################
  1345. # ######################################## START-UP ARGUMENTS ###############################################
  1346. # ###########################################################################################################
  1347. # test if the program was started with a script as parameter
  1348. if self.cmd_line_shellvar:
  1349. try:
  1350. cnt = 0
  1351. command_tcl = 0
  1352. for i in self.cmd_line_shellvar.split(','):
  1353. if i is not None:
  1354. # noinspection PyBroadException
  1355. try:
  1356. command_tcl = eval(i)
  1357. except Exception:
  1358. command_tcl = i
  1359. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1360. cnt += 1
  1361. # if there are Windows paths then replace the path separator with a Unix like one
  1362. if sys.platform == 'win32':
  1363. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1364. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1365. except Exception as ext:
  1366. print("ERROR: ", ext)
  1367. sys.exit(2)
  1368. if self.cmd_line_shellfile:
  1369. if self.cmd_line_headless != 1:
  1370. if self.ui.shell_dock.isHidden():
  1371. self.ui.shell_dock.show()
  1372. try:
  1373. with open(self.cmd_line_shellfile, "r") as myfile:
  1374. # if show_splash:
  1375. # self.splash.showMessage('%s: %ssec\n%s' % (
  1376. # _("Canvas initialization started.\n"
  1377. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1378. # _("Executing Tcl Script ...")),
  1379. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1380. # color=QtGui.QColor("gray"))
  1381. cmd_line_shellfile_text = myfile.read()
  1382. if self.cmd_line_headless != 1:
  1383. self.shell.exec_command(cmd_line_shellfile_text)
  1384. else:
  1385. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1386. except Exception as ext:
  1387. print("ERROR: ", ext)
  1388. sys.exit(2)
  1389. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1390. # the path/file_name must be enclosed in quotes if it contain spaces
  1391. if App.args:
  1392. self.args_at_startup.emit(App.args)
  1393. if self.defaults.old_defaults_found is True:
  1394. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1395. "Please reboot the application to update."))
  1396. self.defaults.old_defaults_found = False
  1397. # ######################################### INIT FINISHED #######################################################
  1398. # #################################################################################################################
  1399. # #################################################################################################################
  1400. # #################################################################################################################
  1401. # #################################################################################################################
  1402. # #################################################################################################################
  1403. @staticmethod
  1404. def copy_and_overwrite(from_path, to_path):
  1405. """
  1406. From here:
  1407. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1408. :param from_path: source path
  1409. :param to_path: destination path
  1410. :return: None
  1411. """
  1412. if os.path.exists(to_path):
  1413. shutil.rmtree(to_path)
  1414. try:
  1415. shutil.copytree(from_path, to_path)
  1416. except FileNotFoundError:
  1417. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1418. shutil.copytree(from_new_path, to_path)
  1419. def on_startup_args(self, args, silent=False):
  1420. """
  1421. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1422. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1423. :param args: a list containing the application args at startup
  1424. :return: None
  1425. """
  1426. if args is not None:
  1427. args_to_process = args
  1428. else:
  1429. args_to_process = App.args
  1430. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1431. for argument in args_to_process:
  1432. if '.FlatPrj'.lower() in argument.lower():
  1433. try:
  1434. project_name = str(argument)
  1435. if project_name == "":
  1436. if silent is False:
  1437. self.inform.emit(_("Cancelled."))
  1438. else:
  1439. # self.open_project(project_name)
  1440. run_from_arg = True
  1441. # self.worker_task.emit({'fcn': self.open_project,
  1442. # 'params': [project_name, run_from_arg]})
  1443. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1444. except Exception as e:
  1445. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1446. elif '.FlatConfig'.lower() in argument.lower():
  1447. try:
  1448. file_name = str(argument)
  1449. if file_name == "":
  1450. if silent is False:
  1451. self.inform.emit(_("Open Config file failed."))
  1452. else:
  1453. run_from_arg = True
  1454. # self.worker_task.emit({'fcn': self.open_config_file,
  1455. # 'params': [file_name, run_from_arg]})
  1456. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1457. except Exception as e:
  1458. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1459. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1460. try:
  1461. file_name = str(argument)
  1462. if file_name == "":
  1463. if silent is False:
  1464. self.inform.emit(_("Open Script file failed."))
  1465. else:
  1466. if silent is False:
  1467. self.on_fileopenscript(name=file_name)
  1468. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1469. self.on_filerunscript(name=file_name)
  1470. except Exception as e:
  1471. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1472. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1473. log.debug("App.on_startup_args() --> Quit event.")
  1474. sys.exit()
  1475. elif 'save'.lower() in argument.lower():
  1476. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1477. self.preferencesUiManager.save_defaults()
  1478. else:
  1479. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1480. proc_arg = argument.lower()
  1481. for ext in exc_list:
  1482. proc_ext = ext.replace(' ', '')
  1483. proc_ext = '.%s' % proc_ext
  1484. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1485. file_name = str(argument)
  1486. if file_name == "":
  1487. if silent is False:
  1488. self.inform.emit(_("Open Excellon file failed."))
  1489. else:
  1490. self.on_fileopenexcellon(name=file_name, signal=None)
  1491. return
  1492. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1493. for ext in gco_list:
  1494. proc_ext = ext.replace(' ', '')
  1495. proc_ext = '.%s' % proc_ext
  1496. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1497. file_name = str(argument)
  1498. if file_name == "":
  1499. if silent is False:
  1500. self.inform.emit(_("Open GCode file failed."))
  1501. else:
  1502. self.on_fileopengcode(name=file_name, signal=None)
  1503. return
  1504. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1505. for ext in grb_list:
  1506. proc_ext = ext.replace(' ', '')
  1507. proc_ext = '.%s' % proc_ext
  1508. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1509. file_name = str(argument)
  1510. if file_name == "":
  1511. if silent is False:
  1512. self.inform.emit(_("Open Gerber file failed."))
  1513. else:
  1514. self.on_fileopengerber(name=file_name, signal=None)
  1515. return
  1516. # if it reached here without already returning then the app was registered with a file that it does not
  1517. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1518. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1519. # for arg in args_to_process:
  1520. # if 'FlatCAM.exe' in arg:
  1521. # continue
  1522. # else:
  1523. # sys.exit(2)
  1524. def set_ui_title(self, name):
  1525. """
  1526. Sets the title of the main window.
  1527. :param name: String that store the project path and project name
  1528. :return: None
  1529. """
  1530. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1531. (self.version,
  1532. ('BETA' if self.beta else ''),
  1533. platform.architecture()[0],
  1534. self.engine,
  1535. name)
  1536. )
  1537. def on_app_restart(self):
  1538. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1539. # be left in the SySTray
  1540. try:
  1541. self.trayIcon.hide()
  1542. except Exception:
  1543. pass
  1544. fcTranslate.restart_program(app=self)
  1545. def clear_pool(self):
  1546. """
  1547. Clear the multiprocessing pool and calls garbage collector.
  1548. :return: None
  1549. """
  1550. self.pool.close()
  1551. self.pool = Pool()
  1552. self.pool_recreated.emit(self.pool)
  1553. gc.collect()
  1554. def install_tools(self):
  1555. """
  1556. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1557. Instantiation of the Tools classes.
  1558. The order that the tools are installed is important as they can depend on each other install position.
  1559. :return: None
  1560. """
  1561. self.distance_tool = Distance(self)
  1562. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1563. before=self.ui.menueditorigin,
  1564. separator=False)
  1565. self.distance_min_tool = DistanceMin(self)
  1566. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1567. pos=self.ui.menuedit,
  1568. before=self.ui.menueditorigin,
  1569. separator=True)
  1570. self.dblsidedtool = DblSidedTool(self)
  1571. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1572. self.cal_exc_tool = ToolCalibration(self)
  1573. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1574. before=self.dblsidedtool.menuAction,
  1575. separator=False)
  1576. self.align_objects_tool = AlignObjects(self)
  1577. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1578. self.edrills_tool = ToolExtractDrills(self)
  1579. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1580. self.panelize_tool = Panelize(self)
  1581. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1582. self.film_tool = Film(self)
  1583. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1584. self.paste_tool = SolderPaste(self)
  1585. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1586. self.calculator_tool = ToolCalculator(self)
  1587. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1588. self.sub_tool = ToolSub(self)
  1589. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1590. pos=self.ui.menutool, separator=True)
  1591. self.rules_tool = RulesCheck(self)
  1592. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1593. pos=self.ui.menutool, separator=False)
  1594. self.optimal_tool = ToolOptimal(self)
  1595. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1596. pos=self.ui.menutool, separator=True)
  1597. self.move_tool = ToolMove(self)
  1598. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1599. before=self.ui.menueditorigin, separator=True)
  1600. self.cutout_tool = CutOut(self)
  1601. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1602. before=self.sub_tool.menuAction)
  1603. self.ncclear_tool = NonCopperClear(self)
  1604. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1605. before=self.sub_tool.menuAction, separator=True)
  1606. self.paint_tool = ToolPaint(self)
  1607. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1608. before=self.sub_tool.menuAction, separator=True)
  1609. self.copper_thieving_tool = ToolCopperThieving(self)
  1610. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1611. pos=self.ui.menutool)
  1612. self.fiducial_tool = ToolFiducials(self)
  1613. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1614. pos=self.ui.menutool)
  1615. self.qrcode_tool = QRCode(self)
  1616. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1617. pos=self.ui.menutool)
  1618. self.punch_tool = ToolPunchGerber(self)
  1619. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1620. self.invert_tool = ToolInvertGerber(self)
  1621. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1622. self.corners_tool = ToolCorners(self)
  1623. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1624. self.transform_tool = ToolTransform(self)
  1625. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1626. pos=self.ui.menuoptions, separator=True)
  1627. self.properties_tool = Properties(self)
  1628. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1629. pos=self.ui.menuoptions)
  1630. self.pdf_tool = ToolPDF(self)
  1631. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1632. pos=self.ui.menufileimport,
  1633. separator=True)
  1634. self.image_tool = ToolImage(self)
  1635. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1636. pos=self.ui.menufileimport,
  1637. separator=True)
  1638. self.pcb_wizard_tool = PcbWizard(self)
  1639. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1640. pos=self.ui.menufileimport)
  1641. self.log.debug("Tools are installed.")
  1642. def remove_tools(self):
  1643. """
  1644. Will remove all the actions in the Tool menu.
  1645. :return: None
  1646. """
  1647. for act in self.ui.menutool.actions():
  1648. self.ui.menutool.removeAction(act)
  1649. def init_tools(self):
  1650. """
  1651. Initialize the Tool tab in the notebook side of the central widget.
  1652. Remove the actions in the Tools menu.
  1653. Instantiate again the FlatCAM tools (plugins).
  1654. All this is required when changing the layout: standard, compact etc.
  1655. :return: None
  1656. """
  1657. log.debug("init_tools()")
  1658. # delete the data currently in the Tools Tab and the Tab itself
  1659. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1660. if widget is not None:
  1661. widget.deleteLater()
  1662. self.ui.notebook.removeTab(2)
  1663. # rebuild the Tools Tab
  1664. self.ui.tool_tab = QtWidgets.QWidget()
  1665. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1666. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1667. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1668. self.ui.tool_scroll_area = VerticalScrollArea()
  1669. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1670. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1671. # first remove all of them
  1672. self.remove_tools()
  1673. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1674. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1675. '&Command Line\tS')
  1676. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1677. # third install all of them
  1678. try:
  1679. self.install_tools()
  1680. except AttributeError:
  1681. pass
  1682. self.log.debug("Tools are initialized.")
  1683. # def parse_system_fonts(self):
  1684. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1685. # 'params': []})
  1686. def connect_toolbar_signals(self):
  1687. """
  1688. Reconnect the signals to the actions in the toolbar.
  1689. This has to be done each time after the FlatCAM tools are removed/installed.
  1690. :return: None
  1691. """
  1692. # Toolbar
  1693. # File Toolbar Signals
  1694. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1695. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1696. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1697. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1698. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1699. # View Toolbar Signals
  1700. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1701. self.ui.replot_btn.triggered.connect(self.plot_all)
  1702. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1703. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1704. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1705. # Edit Toolbar Signals
  1706. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1707. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1708. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1709. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1710. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1711. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1712. self.ui.delete_btn.triggered.connect(self.on_delete)
  1713. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1714. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1715. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1716. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1717. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1718. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1719. # Scripting Toolbar Signals
  1720. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1721. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1722. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1723. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1724. # Tools Toolbar Signals
  1725. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1726. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1727. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1728. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1729. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1730. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1731. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1732. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1733. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1734. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1735. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1736. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1737. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1738. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1739. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1740. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1741. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1742. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1743. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1744. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1745. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1746. def object2editor(self):
  1747. """
  1748. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1749. :return: None
  1750. """
  1751. self.defaults.report_usage("object2editor()")
  1752. # disable the objects menu as it may interfere with the Editors
  1753. self.ui.menuobjects.setDisabled(True)
  1754. edited_object = self.collection.get_active()
  1755. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1756. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1757. pass
  1758. else:
  1759. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1760. return
  1761. if isinstance(edited_object, GeometryObject):
  1762. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1763. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1764. # we set the notebook to hidden
  1765. # self.ui.splitter.setSizes([0, 1])
  1766. if edited_object.multigeo is True:
  1767. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1768. if len(sel_rows) > 1:
  1769. self.inform.emit('[WARNING_NOTCL] %s' %
  1770. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1771. "is not possible.\n"
  1772. "Edit only one geometry at a time."))
  1773. # determine the tool dia of the selected tool
  1774. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1775. # now find the key in the edited_object.tools that has this tooldia
  1776. multi_tool = 1
  1777. for tool in edited_object.tools:
  1778. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1779. multi_tool = tool
  1780. break
  1781. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1782. else:
  1783. self.geo_editor.edit_fcgeometry(edited_object)
  1784. # set call source to the Editor we go into
  1785. self.call_source = 'geo_editor'
  1786. elif isinstance(edited_object, ExcellonObject):
  1787. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1788. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1789. if self.ui.splitter.sizes()[0] == 0:
  1790. self.ui.splitter.setSizes([1, 1])
  1791. self.exc_editor.edit_fcexcellon(edited_object)
  1792. # set call source to the Editor we go into
  1793. self.call_source = 'exc_editor'
  1794. elif isinstance(edited_object, GerberObject):
  1795. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1796. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1797. if self.ui.splitter.sizes()[0] == 0:
  1798. self.ui.splitter.setSizes([1, 1])
  1799. self.grb_editor.edit_fcgerber(edited_object)
  1800. # set call source to the Editor we go into
  1801. self.call_source = 'grb_editor'
  1802. # reset the following variables so the UI is built again after edit
  1803. edited_object.ui_build = False
  1804. edited_object.build_aperture_storage = False
  1805. elif isinstance(edited_object, CNCJobObject):
  1806. if self.ui.splitter.sizes()[0] == 0:
  1807. self.ui.splitter.setSizes([1, 1])
  1808. edited_object.on_edit_code_click()
  1809. return
  1810. # make sure that we can't select another object while in Editor Mode:
  1811. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1812. self.ui.project_frame.setDisabled(True)
  1813. # delete any selection shape that might be active as they are not relevant in Editor
  1814. self.delete_selection_shape()
  1815. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1816. self.ui.plot_tab_area.protectTab(0)
  1817. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1818. self.should_we_save = True
  1819. def editor2object(self, cleanup=None):
  1820. """
  1821. Transfers the Geometry or Excellon from it's editor to the current object.
  1822. :return: None
  1823. """
  1824. self.defaults.report_usage("editor2object()")
  1825. # re-enable the objects menu that was disabled on entry in Editor mode
  1826. self.ui.menuobjects.setDisabled(False)
  1827. # do not update a geometry or excellon object unless it comes out of an editor
  1828. if self.call_source != 'app':
  1829. edited_obj = self.collection.get_active()
  1830. if cleanup is None:
  1831. msgbox = QtWidgets.QMessageBox()
  1832. msgbox.setText(_("Do you want to save the edited object?"))
  1833. msgbox.setWindowTitle(_("Close Editor"))
  1834. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1835. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1836. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1837. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1838. msgbox.setDefaultButton(bt_yes)
  1839. msgbox.exec_()
  1840. response = msgbox.clickedButton()
  1841. if response == bt_yes:
  1842. # clean the Tools Tab
  1843. self.ui.tool_scroll_area.takeWidget()
  1844. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1845. self.ui.notebook.setTabText(2, "Tool")
  1846. if isinstance(edited_obj, GeometryObject):
  1847. obj_type = "Geometry"
  1848. if cleanup is None:
  1849. self.geo_editor.update_fcgeometry(edited_obj)
  1850. # self.geo_editor.update_options(edited_obj)
  1851. self.geo_editor.deactivate()
  1852. # restore GUI to the Selected TAB
  1853. # Remove anything else in the GUI
  1854. self.ui.tool_scroll_area.takeWidget()
  1855. # update the geo object options so it is including the bounding box values
  1856. try:
  1857. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1858. edited_obj.options['xmin'] = xmin
  1859. edited_obj.options['ymin'] = ymin
  1860. edited_obj.options['xmax'] = xmax
  1861. edited_obj.options['ymax'] = ymax
  1862. except AttributeError as e:
  1863. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1864. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1865. edited_obj.build_ui()
  1866. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1867. elif isinstance(edited_obj, GerberObject):
  1868. obj_type = "Gerber"
  1869. if cleanup is None:
  1870. self.grb_editor.update_fcgerber()
  1871. self.grb_editor.update_options(edited_obj)
  1872. self.grb_editor.deactivate_grb_editor()
  1873. # delete the old object (the source object) if it was an empty one
  1874. try:
  1875. if len(edited_obj.solid_geometry) == 0:
  1876. old_name = edited_obj.options['name']
  1877. self.collection.set_active(old_name)
  1878. self.collection.delete_active()
  1879. except TypeError:
  1880. # if the solid_geometry is a single Polygon the len() will not work
  1881. # in any case, falling here means that we have something in the solid_geometry, even if only
  1882. # a single Polygon, therefore we pass this
  1883. pass
  1884. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1885. # restore GUI to the Selected TAB
  1886. # Remove anything else in the GUI
  1887. self.ui.selected_scroll_area.takeWidget()
  1888. elif isinstance(edited_obj, ExcellonObject):
  1889. obj_type = "Excellon"
  1890. if cleanup is None:
  1891. self.exc_editor.update_fcexcellon(edited_obj)
  1892. # self.exc_editor.update_options(edited_obj)
  1893. self.exc_editor.deactivate()
  1894. # restore GUI to the Selected TAB
  1895. # Remove anything else in the GUI
  1896. self.ui.tool_scroll_area.takeWidget()
  1897. # delete the old object (the source object) if it was an empty one
  1898. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1899. old_name = edited_obj.options['name']
  1900. self.collection.delete_by_name(name=old_name)
  1901. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1902. else:
  1903. self.inform.emit('[WARNING_NOTCL] %s' %
  1904. _("Select a Gerber, Geometry or Excellon Object to update."))
  1905. return
  1906. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1907. elif response == bt_no:
  1908. # clean the Tools Tab
  1909. self.ui.tool_scroll_area.takeWidget()
  1910. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1911. self.ui.notebook.setTabText(2, "Tool")
  1912. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1913. if isinstance(edited_obj, GeometryObject):
  1914. self.geo_editor.deactivate()
  1915. edited_obj.build_ui()
  1916. elif isinstance(edited_obj, GerberObject):
  1917. self.grb_editor.deactivate_grb_editor()
  1918. edited_obj.build_ui()
  1919. elif isinstance(edited_obj, ExcellonObject):
  1920. self.exc_editor.deactivate()
  1921. edited_obj.build_ui()
  1922. else:
  1923. self.inform.emit('[WARNING_NOTCL] %s' %
  1924. _("Select a Gerber, Geometry or Excellon Object to update."))
  1925. return
  1926. elif response == bt_cancel:
  1927. return
  1928. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1929. # edited_obj.build_ui()
  1930. # Switch notebook to Selected page
  1931. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1932. else:
  1933. if isinstance(edited_obj, GeometryObject):
  1934. self.geo_editor.deactivate()
  1935. elif isinstance(edited_obj, GerberObject):
  1936. self.grb_editor.deactivate_grb_editor()
  1937. elif isinstance(edited_obj, ExcellonObject):
  1938. self.exc_editor.deactivate()
  1939. else:
  1940. self.inform.emit('[WARNING_NOTCL] %s' %
  1941. _("Select a Gerber, Geometry or Excellon Object to update."))
  1942. return
  1943. # if notebook is hidden we show it
  1944. if self.ui.splitter.sizes()[0] == 0:
  1945. self.ui.splitter.setSizes([1, 1])
  1946. # restore the call_source to app
  1947. self.call_source = 'app'
  1948. edited_obj.plot()
  1949. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1950. self.ui.plot_tab_area.protectTab(0)
  1951. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1952. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1953. self.ui.project_frame.setDisabled(False)
  1954. def get_last_folder(self):
  1955. """
  1956. Get the folder path from where the last file was opened.
  1957. :return: String, last opened folder path
  1958. """
  1959. return self.defaults["global_last_folder"]
  1960. def get_last_save_folder(self):
  1961. """
  1962. Get the folder path from where the last file was saved.
  1963. :return: String, last saved folder path
  1964. """
  1965. loc = self.defaults["global_last_save_folder"]
  1966. if loc is None:
  1967. loc = self.defaults["global_last_folder"]
  1968. if loc is None:
  1969. loc = os.path.dirname(__file__)
  1970. return loc
  1971. def info(self, msg):
  1972. """
  1973. Informs the user. Normally on the status bar, optionally
  1974. also on the shell.
  1975. :param msg: Text to write.
  1976. :return: None
  1977. """
  1978. # Type of message in brackets at the beginning of the message.
  1979. match = re.search(r"\[(.*)\](.*)", msg)
  1980. if match:
  1981. level = match.group(1)
  1982. msg_ = match.group(2)
  1983. self.ui.fcinfo.set_status(str(msg_), level=level)
  1984. if level.lower() == "error":
  1985. self.shell_message(msg, error=True, show=True)
  1986. elif level.lower() == "warning":
  1987. self.shell_message(msg, warning=True, show=True)
  1988. elif level.lower() == "error_notcl":
  1989. self.shell_message(msg, error=True, show=False)
  1990. elif level.lower() == "warning_notcl":
  1991. self.shell_message(msg, warning=True, show=False)
  1992. elif level.lower() == "success":
  1993. self.shell_message(msg, success=True, show=False)
  1994. elif level.lower() == "selected":
  1995. self.shell_message(msg, selected=True, show=False)
  1996. else:
  1997. self.shell_message(msg, show=False)
  1998. else:
  1999. self.ui.fcinfo.set_status(str(msg), level="info")
  2000. # make sure that if the message is to clear the infobar with a space
  2001. # is not printed over and over on the shell
  2002. if msg != '':
  2003. self.shell_message(msg)
  2004. def restore_toolbar_view(self):
  2005. """
  2006. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2007. was saved in the defaults dictionary.
  2008. :return: None
  2009. """
  2010. tb = self.defaults["global_toolbar_view"]
  2011. if tb & 1:
  2012. self.ui.toolbarfile.setVisible(True)
  2013. else:
  2014. self.ui.toolbarfile.setVisible(False)
  2015. if tb & 2:
  2016. self.ui.toolbargeo.setVisible(True)
  2017. else:
  2018. self.ui.toolbargeo.setVisible(False)
  2019. if tb & 4:
  2020. self.ui.toolbarview.setVisible(True)
  2021. else:
  2022. self.ui.toolbarview.setVisible(False)
  2023. if tb & 8:
  2024. self.ui.toolbartools.setVisible(True)
  2025. else:
  2026. self.ui.toolbartools.setVisible(False)
  2027. if tb & 16:
  2028. self.ui.exc_edit_toolbar.setVisible(True)
  2029. else:
  2030. self.ui.exc_edit_toolbar.setVisible(False)
  2031. if tb & 32:
  2032. self.ui.geo_edit_toolbar.setVisible(True)
  2033. else:
  2034. self.ui.geo_edit_toolbar.setVisible(False)
  2035. if tb & 64:
  2036. self.ui.grb_edit_toolbar.setVisible(True)
  2037. else:
  2038. self.ui.grb_edit_toolbar.setVisible(False)
  2039. if tb & 128:
  2040. self.ui.snap_toolbar.setVisible(True)
  2041. else:
  2042. self.ui.snap_toolbar.setVisible(False)
  2043. if tb & 256:
  2044. self.ui.toolbarshell.setVisible(True)
  2045. else:
  2046. self.ui.toolbarshell.setVisible(False)
  2047. def on_import_preferences(self):
  2048. """
  2049. Loads the application default settings from a saved file into
  2050. ``self.defaults`` dictionary.
  2051. :return: None
  2052. """
  2053. self.defaults.report_usage("on_import_preferences")
  2054. App.log.debug("App.on_import_preferences()")
  2055. # Show file chooser
  2056. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2057. try:
  2058. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2059. directory=self.data_path,
  2060. filter=filter_)
  2061. except TypeError:
  2062. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2063. filter=filter_)
  2064. filename = str(filename)
  2065. if filename == "":
  2066. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2067. return
  2068. # Load in the defaults from the chosen file
  2069. self.defaults.load(filename=filename)
  2070. self.preferencesUiManager.on_preferences_edited()
  2071. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2072. def on_export_preferences(self):
  2073. """
  2074. Save the defaults dictionary to a file.
  2075. :return: None
  2076. """
  2077. self.defaults.report_usage("on_export_preferences")
  2078. App.log.debug("on_export_preferences()")
  2079. # defaults_file_content = None
  2080. # Show file chooser
  2081. date = str(datetime.today()).rpartition('.')[0]
  2082. date = ''.join(c for c in date if c not in ':-')
  2083. date = date.replace(' ', '_')
  2084. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2085. try:
  2086. filename, _f = FCFileSaveDialog.get_saved_filename(
  2087. caption=_("Export FlatCAM Preferences"),
  2088. directory=self.data_path + '/preferences_' + date,
  2089. filter=filter__
  2090. )
  2091. except TypeError:
  2092. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2093. filename = str(filename)
  2094. if filename == "":
  2095. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2096. return
  2097. # Update options
  2098. self.preferencesUiManager.defaults_read_form()
  2099. self.defaults.propagate_defaults()
  2100. # Save update options
  2101. try:
  2102. self.defaults.write(filename=filename)
  2103. except Exception:
  2104. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2105. return
  2106. if self.defaults["global_open_style"] is False:
  2107. self.file_opened.emit("preferences", filename)
  2108. self.file_saved.emit("preferences", filename)
  2109. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2110. def save_to_file(self, content_to_save, txt_content):
  2111. """
  2112. Save something to a file.
  2113. :return: None
  2114. """
  2115. self.defaults.report_usage("save_to_file")
  2116. App.log.debug("save_to_file()")
  2117. self.date = str(datetime.today()).rpartition('.')[0]
  2118. self.date = ''.join(c for c in self.date if c not in ':-')
  2119. self.date = self.date.replace(' ', '_')
  2120. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2121. path_to_save = self.defaults["global_last_save_folder"] if \
  2122. self.defaults["global_last_save_folder"] is not None else self.data_path
  2123. try:
  2124. filename, _f = FCFileSaveDialog.get_saved_filename(
  2125. caption=_("Save to file"),
  2126. directory=path_to_save + '/file_' + self.date,
  2127. filter=filter__
  2128. )
  2129. except TypeError:
  2130. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2131. filename = str(filename)
  2132. if filename == "":
  2133. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2134. return
  2135. else:
  2136. try:
  2137. with open(filename, 'w') as f:
  2138. ___ = f.read()
  2139. except PermissionError:
  2140. self.inform.emit('[WARNING] %s' %
  2141. _("Permission denied, saving not possible.\n"
  2142. "Most likely another app is holding the file open and not accessible."))
  2143. return
  2144. except IOError:
  2145. App.log.debug('Creating a new file ...')
  2146. f = open(filename, 'w')
  2147. f.close()
  2148. except Exception:
  2149. e = sys.exc_info()[0]
  2150. App.log.error("Could not load the file.")
  2151. App.log.error(str(e))
  2152. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2153. return
  2154. # Save content
  2155. if filename.rpartition('.')[2].lower() == 'html':
  2156. file_content = content_to_save
  2157. else:
  2158. file_content = txt_content
  2159. try:
  2160. with open(filename, "w") as f:
  2161. f.write(file_content)
  2162. except Exception:
  2163. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2164. return
  2165. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2166. def save_geometry(self, x, y, width, height, notebook_width):
  2167. """
  2168. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2169. launch of the application.
  2170. :param x: X position of the main window
  2171. :param y: Y position of the main window
  2172. :param width: width of the main window
  2173. :param height: height of the main window
  2174. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2175. :return: None
  2176. """
  2177. self.defaults["global_def_win_x"] = x
  2178. self.defaults["global_def_win_y"] = y
  2179. self.defaults["global_def_win_w"] = width
  2180. self.defaults["global_def_win_h"] = height
  2181. self.defaults["global_def_notebook_width"] = notebook_width
  2182. self.preferencesUiManager.save_defaults()
  2183. def restore_main_win_geom(self):
  2184. try:
  2185. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2186. self.defaults["global_def_win_y"],
  2187. self.defaults["global_def_win_w"],
  2188. self.defaults["global_def_win_h"])
  2189. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2190. except KeyError as e:
  2191. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2192. def message_dialog(self, title, message, kind="info"):
  2193. """
  2194. Builds and show a custom QMessageBox to be used in FlatCAM.
  2195. :param title: title of the QMessageBox
  2196. :param message: message to be displayed
  2197. :param kind: type of QMessageBox; will display a specific icon.
  2198. :return:
  2199. """
  2200. icon = {"info": QtWidgets.QMessageBox.Information,
  2201. "warning": QtWidgets.QMessageBox.Warning,
  2202. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2203. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2204. dlg.setText(message)
  2205. dlg.exec_()
  2206. def register_recent(self, kind, filename):
  2207. """
  2208. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2209. dictionary.
  2210. :param kind: type of file that was opened
  2211. :param filename: the path and file name for the file that was opened
  2212. :return:
  2213. """
  2214. self.log.debug("register_recent()")
  2215. self.log.debug(" %s" % kind)
  2216. self.log.debug(" %s" % filename)
  2217. record = {'kind': str(kind), 'filename': str(filename)}
  2218. if record in self.recent:
  2219. return
  2220. if record in self.recent_projects:
  2221. return
  2222. if record['kind'] == 'project':
  2223. self.recent_projects.insert(0, record)
  2224. else:
  2225. self.recent.insert(0, record)
  2226. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2227. self.recent.pop()
  2228. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2229. self.recent_projects.pop()
  2230. try:
  2231. f = open(self.data_path + '/recent.json', 'w')
  2232. except IOError:
  2233. App.log.error("Failed to open recent items file for writing.")
  2234. self.inform.emit('[ERROR_NOTCL] %s' %
  2235. _('Failed to open recent files file for writing.'))
  2236. return
  2237. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2238. f.close()
  2239. try:
  2240. fp = open(self.data_path + '/recent_projects.json', 'w')
  2241. except IOError:
  2242. App.log.error("Failed to open recent items file for writing.")
  2243. self.inform.emit('[ERROR_NOTCL] %s' %
  2244. _('Failed to open recent projects file for writing.'))
  2245. return
  2246. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2247. fp.close()
  2248. # Re-build the recent items menu
  2249. self.setup_recent_items()
  2250. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2251. """
  2252. Creates a new specialized FlatCAMObj and attaches it to the application,
  2253. this is, updates the GUI accordingly, any other records and plots it.
  2254. This method is thread-safe.
  2255. Notes:
  2256. * If the name is in use, the self.collection will modify it
  2257. when appending it to the collection. There is no need to handle
  2258. name conflicts here.
  2259. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2260. :type kind: str
  2261. :param name: Name for the object.
  2262. :type name: str
  2263. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2264. The function is called with 2 parameters: the new object and the App instance.
  2265. :type initialize: function
  2266. :param plot: If to plot the resulting object
  2267. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2268. self.collection
  2269. :return: None
  2270. :rtype: None
  2271. """
  2272. App.log.debug("new_object()")
  2273. obj_plot = plot
  2274. obj_autoselected = autoselected
  2275. t0 = time.time() # Debug
  2276. # ## Create object
  2277. classdict = {
  2278. "gerber": GerberObject,
  2279. "excellon": ExcellonObject,
  2280. "cncjob": CNCJobObject,
  2281. "geometry": GeometryObject,
  2282. "script": ScriptObject,
  2283. "document": DocumentObject
  2284. }
  2285. App.log.debug("Calling object constructor...")
  2286. # Object creation/instantiation
  2287. obj = classdict[kind](name)
  2288. obj.units = self.options["units"]
  2289. # IMPORTANT
  2290. # The key names in defaults and options dictionary's are not random:
  2291. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2292. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2293. # copied to self.options. After that, below, depending on the type of
  2294. # object that is created, it will strip the name of the object and the underline (if the original key was
  2295. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2296. # "toolchange"
  2297. for option in self.options:
  2298. if option.find(kind + "_") == 0:
  2299. oname = option[len(kind) + 1:]
  2300. obj.options[oname] = self.options[option]
  2301. obj.isHovering = False
  2302. obj.notHovering = True
  2303. # Initialize as per user request
  2304. # User must take care to implement initialize
  2305. # in a thread-safe way as is is likely that we
  2306. # have been invoked in a separate thread.
  2307. t1 = time.time()
  2308. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2309. try:
  2310. return_value = initialize(obj, self)
  2311. except Exception as e:
  2312. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2313. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2314. msg += traceback.format_exc()
  2315. self.inform.emit(msg)
  2316. return "fail"
  2317. t2 = time.time()
  2318. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2319. if return_value == 'fail':
  2320. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2321. return "fail"
  2322. # Check units and convert if necessary
  2323. # This condition CAN be true because initialize() can change obj.units
  2324. if self.options["units"].upper() != obj.units.upper():
  2325. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2326. obj.convert_units(self.options["units"])
  2327. t3 = time.time()
  2328. self.log.debug("%f seconds converting units." % (t3 - t2))
  2329. # Create the bounding box for the object and then add the results to the obj.options
  2330. # But not for Scripts or for Documents
  2331. if kind != 'document' and kind != 'script':
  2332. try:
  2333. xmin, ymin, xmax, ymax = obj.bounds()
  2334. obj.options['xmin'] = xmin
  2335. obj.options['ymin'] = ymin
  2336. obj.options['xmax'] = xmax
  2337. obj.options['ymax'] = ymax
  2338. except Exception as e:
  2339. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2340. return "fail"
  2341. try:
  2342. if kind == 'excellon':
  2343. obj.fill_color = self.defaults["excellon_plot_fill"]
  2344. obj.outline_color = self.defaults["excellon_plot_line"]
  2345. if kind == 'gerber':
  2346. obj.fill_color = self.defaults["gerber_plot_fill"]
  2347. obj.outline_color = self.defaults["gerber_plot_line"]
  2348. except Exception as e:
  2349. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2350. # update the KeyWords list with the name of the file
  2351. self.myKeywords.append(obj.options['name'])
  2352. log.debug("Moving new object back to main thread.")
  2353. # Move the object to the main thread and let the app know that it is available.
  2354. obj.moveToThread(self.main_thread)
  2355. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2356. return obj
  2357. def new_excellon_object(self):
  2358. """
  2359. Creates a new, blank Excellon object.
  2360. :return: None
  2361. """
  2362. self.defaults.report_usage("new_excellon_object()")
  2363. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2364. def new_geometry_object(self):
  2365. """
  2366. Creates a new, blank and single-tool Geometry object.
  2367. :return: None
  2368. """
  2369. self.defaults.report_usage("new_geometry_object()")
  2370. def initialize(obj, app):
  2371. obj.multitool = False
  2372. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2373. def new_gerber_object(self):
  2374. """
  2375. Creates a new, blank Gerber object.
  2376. :return: None
  2377. """
  2378. self.defaults.report_usage("new_gerber_object()")
  2379. def initialize(grb_obj, app):
  2380. grb_obj.multitool = False
  2381. grb_obj.source_file = []
  2382. grb_obj.multigeo = False
  2383. grb_obj.follow = False
  2384. grb_obj.apertures = {}
  2385. grb_obj.solid_geometry = []
  2386. try:
  2387. grb_obj.options['xmin'] = 0
  2388. grb_obj.options['ymin'] = 0
  2389. grb_obj.options['xmax'] = 0
  2390. grb_obj.options['ymax'] = 0
  2391. except KeyError:
  2392. pass
  2393. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2394. def new_script_object(self):
  2395. """
  2396. Creates a new, blank TCL Script object.
  2397. :return: None
  2398. """
  2399. self.defaults.report_usage("new_script_object()")
  2400. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2401. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2402. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2403. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2404. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2405. # "ListSys, MillDrills,\n" \
  2406. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2407. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2408. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2409. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2410. # "# SubtractRectangle, Version, WriteGCode\n"
  2411. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2412. '# %s:\n' % _('TCL Tutorial is here') + \
  2413. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2414. '# %s:\n' % _("FlatCAM commands list")
  2415. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2416. "(displayed in Tcl Shell).")
  2417. def initialize(obj, app):
  2418. obj.source_file = deepcopy(new_source_file)
  2419. outname = 'new_script'
  2420. self.new_object('script', outname, initialize, plot=False)
  2421. def new_document_object(self):
  2422. """
  2423. Creates a new, blank Document object.
  2424. :return: None
  2425. """
  2426. self.defaults.report_usage("new_document_object()")
  2427. def initialize(obj, app):
  2428. obj.source_file = ""
  2429. self.new_object('document', 'new_document', initialize, plot=False)
  2430. def on_object_created(self, obj, plot, auto_select):
  2431. """
  2432. Event callback for object creation.
  2433. It will add the new object to the collection. After that it will plot the object in a threaded way
  2434. :param obj: The newly created FlatCAM object.
  2435. :param plot: if the newly create object t obe plotted
  2436. :param auto_select: if the newly created object to be autoselected after creation
  2437. :return: None
  2438. """
  2439. t0 = time.time() # DEBUG
  2440. self.log.debug("on_object_created()")
  2441. # The Collection might change the name if there is a collision
  2442. self.collection.append(obj)
  2443. # after adding the object to the collection always update the list of objects that are in the collection
  2444. self.all_objects_list = self.collection.get_list()
  2445. # self.inform.emit('[selected] %s created & selected: %s' %
  2446. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2447. if obj.kind == 'gerber':
  2448. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2449. kind=obj.kind.capitalize(),
  2450. color='green',
  2451. name=str(obj.options['name']), tx=_("created/selected"))
  2452. )
  2453. elif obj.kind == 'excellon':
  2454. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2455. kind=obj.kind.capitalize(),
  2456. color='brown',
  2457. name=str(obj.options['name']), tx=_("created/selected"))
  2458. )
  2459. elif obj.kind == 'cncjob':
  2460. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2461. kind=obj.kind.capitalize(),
  2462. color='blue',
  2463. name=str(obj.options['name']), tx=_("created/selected"))
  2464. )
  2465. elif obj.kind == 'geometry':
  2466. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2467. kind=obj.kind.capitalize(),
  2468. color='red',
  2469. name=str(obj.options['name']), tx=_("created/selected"))
  2470. )
  2471. elif obj.kind == 'script':
  2472. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2473. kind=obj.kind.capitalize(),
  2474. color='orange',
  2475. name=str(obj.options['name']), tx=_("created/selected"))
  2476. )
  2477. elif obj.kind == 'document':
  2478. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2479. kind=obj.kind.capitalize(),
  2480. color='darkCyan',
  2481. name=str(obj.options['name']), tx=_("created/selected"))
  2482. )
  2483. # update the SHELL auto-completer model with the name of the new object
  2484. self.shell._edit.set_model_data(self.myKeywords)
  2485. if auto_select:
  2486. # select the just opened object but deselect the previous ones
  2487. self.collection.set_all_inactive()
  2488. self.collection.set_active(obj.options["name"])
  2489. else:
  2490. self.collection.set_all_inactive()
  2491. # here it is done the object plotting
  2492. def worker_task(t_obj):
  2493. with self.proc_container.new(_("Plotting")):
  2494. if isinstance(t_obj, CNCJobObject):
  2495. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2496. else:
  2497. t_obj.plot()
  2498. t1 = time.time() # DEBUG
  2499. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2500. self.object_plotted.emit(t_obj)
  2501. # Send to worker
  2502. # self.worker.add_task(worker_task, [self])
  2503. if plot is True:
  2504. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2505. def on_object_changed(self, obj):
  2506. """
  2507. Called whenever the geometry of the object was changed in some way.
  2508. This require the update of it's bounding values so it can be the selected on canvas.
  2509. Update the bounding box data from obj.options
  2510. :param obj: the object that was changed
  2511. :return: None
  2512. """
  2513. xmin, ymin, xmax, ymax = obj.bounds()
  2514. obj.options['xmin'] = xmin
  2515. obj.options['ymin'] = ymin
  2516. obj.options['xmax'] = xmax
  2517. obj.options['ymax'] = ymax
  2518. log.debug("Object changed, updating the bounding box data on self.options")
  2519. # delete the old selection shape
  2520. self.delete_selection_shape()
  2521. self.should_we_save = True
  2522. def on_object_plotted(self):
  2523. """
  2524. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2525. :return: None
  2526. """
  2527. self.on_zoom_fit(None)
  2528. def on_about(self):
  2529. """
  2530. Displays the "about" dialog found in the Menu --> Help.
  2531. :return: None
  2532. """
  2533. self.defaults.report_usage("on_about")
  2534. version = self.version
  2535. version_date = self.version_date
  2536. beta = self.beta
  2537. class AboutDialog(QtWidgets.QDialog):
  2538. def __init__(self, app, parent=None):
  2539. QtWidgets.QDialog.__init__(self, parent)
  2540. self.app = app
  2541. # Icon and title
  2542. self.setWindowIcon(parent.app_icon)
  2543. self.setWindowTitle(_("About FlatCAM"))
  2544. self.resize(600, 200)
  2545. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2546. # self.setStyleSheet(
  2547. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2548. # "background-attachment: fixed"
  2549. # )
  2550. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2551. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2552. # palette = QtGui.QPalette()
  2553. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2554. # self.setPalette(palette)
  2555. logo = QtWidgets.QLabel()
  2556. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2557. title = QtWidgets.QLabel(
  2558. "<font size=8><B>FlatCAM</B></font><BR>"
  2559. "{title}<BR>"
  2560. "<BR>"
  2561. "<BR>"
  2562. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2563. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2564. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2565. "<B>{issue}</B></a><BR>".format(
  2566. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2567. devel=_("Development"),
  2568. down=_("DOWNLOAD"),
  2569. issue=_("Issue tracker"))
  2570. )
  2571. title.setOpenExternalLinks(True)
  2572. closebtn = QtWidgets.QPushButton(_("Close"))
  2573. tab_widget = QtWidgets.QTabWidget()
  2574. description_label = QtWidgets.QLabel(
  2575. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2576. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2577. version=version,
  2578. beta=('BETA' if beta else ''),
  2579. date=version_date,
  2580. arch=platform.architecture()[0])
  2581. )
  2582. description_label.setOpenExternalLinks(True)
  2583. lic_lbl_header = QtWidgets.QLabel(
  2584. '%s:<br>%s<br>' % (
  2585. _('Licensed under the MIT license'),
  2586. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2587. "http://www.opensource.org/licenses/mit-license.php</a>"
  2588. )
  2589. )
  2590. lic_lbl_header.setOpenExternalLinks(True)
  2591. lic_lbl_body = QtWidgets.QLabel(
  2592. _(
  2593. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2594. 'of this software and associated documentation files (the "Software"), to deal\n'
  2595. 'in the Software without restriction, including without limitation the rights\n'
  2596. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2597. 'copies of the Software, and to permit persons to whom the Software is\n'
  2598. 'furnished to do so, subject to the following conditions:\n\n'
  2599. 'The above copyright notice and this permission notice shall be included in\n'
  2600. 'all copies or substantial portions of the Software.\n\n'
  2601. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2602. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2603. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2604. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2605. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2606. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2607. 'THE SOFTWARE.'
  2608. )
  2609. )
  2610. attributions_label = QtWidgets.QLabel(
  2611. _(
  2612. 'Some of the icons used are from the following sources:<br>'
  2613. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2614. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2615. 'title="Flaticon">www.flaticon.com</a></div>'
  2616. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2617. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2618. )
  2619. )
  2620. attributions_label.setOpenExternalLinks(True)
  2621. # layouts
  2622. layout1 = QtWidgets.QVBoxLayout()
  2623. layout1_1 = QtWidgets.QHBoxLayout()
  2624. layout1_2 = QtWidgets.QHBoxLayout()
  2625. layout2 = QtWidgets.QHBoxLayout()
  2626. layout3 = QtWidgets.QHBoxLayout()
  2627. self.setLayout(layout1)
  2628. layout1.addLayout(layout1_1)
  2629. layout1.addLayout(layout1_2)
  2630. layout1.addLayout(layout2)
  2631. layout1.addLayout(layout3)
  2632. layout1_1.addStretch()
  2633. layout1_1.addWidget(description_label)
  2634. layout1_2.addWidget(tab_widget)
  2635. self.splash_tab = QtWidgets.QWidget()
  2636. self.splash_tab.setObjectName("splash_about")
  2637. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2638. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.splash_tab, _("Splash"))
  2640. self.programmmers_tab = QtWidgets.QWidget()
  2641. self.programmmers_tab.setObjectName("programmers_about")
  2642. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2643. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2645. self.translators_tab = QtWidgets.QWidget()
  2646. self.translators_tab.setObjectName("translators_about")
  2647. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2648. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2649. tab_widget.addTab(self.translators_tab, _("Translators"))
  2650. self.license_tab = QtWidgets.QWidget()
  2651. self.license_tab.setObjectName("license_about")
  2652. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2653. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2654. tab_widget.addTab(self.license_tab, _("License"))
  2655. self.attributions_tab = QtWidgets.QWidget()
  2656. self.attributions_tab.setObjectName("attributions_about")
  2657. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2658. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2659. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2660. self.splash_tab_layout.addWidget(logo, stretch=0)
  2661. self.splash_tab_layout.addWidget(title, stretch=1)
  2662. pal = QtGui.QPalette()
  2663. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2664. self.prog_grid_lay = QtWidgets.QGridLayout()
  2665. self.prog_grid_lay.setHorizontalSpacing(20)
  2666. self.prog_grid_lay.setColumnStretch(0, 0)
  2667. self.prog_grid_lay.setColumnStretch(2, 1)
  2668. prog_widget = QtWidgets.QWidget()
  2669. prog_widget.setLayout(self.prog_grid_lay)
  2670. prog_scroll = QtWidgets.QScrollArea()
  2671. prog_scroll.setWidget(prog_widget)
  2672. prog_scroll.setWidgetResizable(True)
  2673. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2674. prog_scroll.setPalette(pal)
  2675. self.programmmers_tab_layout.addWidget(prog_scroll)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2713. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2714. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2715. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2716. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2717. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2718. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2719. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2720. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2721. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2722. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2723. self.translator_grid_lay = QtWidgets.QGridLayout()
  2724. self.translator_grid_lay.setColumnStretch(0, 0)
  2725. self.translator_grid_lay.setColumnStretch(1, 0)
  2726. self.translator_grid_lay.setColumnStretch(2, 1)
  2727. self.translator_grid_lay.setColumnStretch(3, 0)
  2728. # trans_widget = QtWidgets.QWidget()
  2729. # trans_widget.setLayout(self.translator_grid_lay)
  2730. # self.translators_tab_layout.addWidget(trans_widget)
  2731. # self.translators_tab_layout.addStretch()
  2732. trans_widget = QtWidgets.QWidget()
  2733. trans_widget.setLayout(self.translator_grid_lay)
  2734. trans_scroll = QtWidgets.QScrollArea()
  2735. trans_scroll.setWidget(trans_widget)
  2736. trans_scroll.setWidgetResizable(True)
  2737. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2738. trans_scroll.setPalette(pal)
  2739. self.translators_tab_layout.addWidget(trans_scroll)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2756. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2757. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2758. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2759. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2760. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2761. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2762. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2763. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2764. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2765. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2766. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2767. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2768. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2769. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2770. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2771. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2772. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2773. self.translator_grid_lay.setColumnStretch(0, 0)
  2774. self.translators_tab_layout.addStretch()
  2775. self.license_tab_layout.addWidget(lic_lbl_header)
  2776. self.license_tab_layout.addWidget(lic_lbl_body)
  2777. self.license_tab_layout.addStretch()
  2778. self.attributions_tab_layout.addWidget(attributions_label)
  2779. self.attributions_tab_layout.addStretch()
  2780. layout3.addStretch()
  2781. layout3.addWidget(closebtn)
  2782. closebtn.clicked.connect(self.accept)
  2783. AboutDialog(app=self, parent=self.ui).exec_()
  2784. def install_bookmarks(self, book_dict=None):
  2785. """
  2786. Install the bookmarks actions in the Help menu -> Bookmarks
  2787. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2788. :return: None
  2789. """
  2790. if book_dict is None:
  2791. self.defaults["global_bookmarks"].update(
  2792. {
  2793. '1': ['FlatCAM', "http://flatcam.org"],
  2794. '2': ['Backup Site', ""]
  2795. }
  2796. )
  2797. else:
  2798. self.defaults["global_bookmarks"].clear()
  2799. self.defaults["global_bookmarks"].update(book_dict)
  2800. # first try to disconnect if somehow they get connected from elsewhere
  2801. for act in self.ui.menuhelp_bookmarks.actions():
  2802. try:
  2803. act.triggered.disconnect()
  2804. except TypeError:
  2805. pass
  2806. # clear all actions except the last one who is the Bookmark manager
  2807. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2808. pass
  2809. else:
  2810. self.ui.menuhelp_bookmarks.removeAction(act)
  2811. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2812. if self.defaults["global_bookmarks"]:
  2813. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2814. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2815. # the JSON is first making the keys as strings (therefore I have to use strings too
  2816. # or do the conversion :(
  2817. # )
  2818. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2819. # the '10' entry jsut after '1' therefore ordering as strings
  2820. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2821. key=lambda x: int(x[0]))
  2822. for entry, bookmark in sorted_bookmarks:
  2823. title = bookmark[0]
  2824. weblink = bookmark[1]
  2825. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2826. act.setText(title)
  2827. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2828. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2829. if title == 'Backup Site' and weblink == "":
  2830. act.triggered.connect(self.on_backup_site)
  2831. else:
  2832. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2833. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2834. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2835. def on_bookmarks_manager(self):
  2836. """
  2837. Adds the bookmark manager in a Tab in Plot Area
  2838. :return:
  2839. """
  2840. for idx in range(self.ui.plot_tab_area.count()):
  2841. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2842. # there can be only one instance of Bookmark Manager at one time
  2843. return
  2844. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2845. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2846. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2847. # add the tab if it was closed
  2848. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2849. # delete the absolute and relative position and messages in the infobar
  2850. self.ui.position_label.setText("")
  2851. # self.ui.rel_position_label.setText("")
  2852. # Switch plot_area to preferences page
  2853. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2854. def on_backup_site(self):
  2855. msgbox = QtWidgets.QMessageBox()
  2856. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2857. "1. FlatCAM.org website is down\n"
  2858. "2. Someone forked FlatCAM project and wants to point\n"
  2859. "to his own website\n\n"
  2860. "If you can't get any informations about FlatCAM beta\n"
  2861. "use the YouTube channel link from the Help menu."))
  2862. msgbox.setWindowTitle(_("Alternative website"))
  2863. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2864. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2865. msgbox.setDefaultButton(bt_yes)
  2866. msgbox.exec_()
  2867. # response = msgbox.clickedButton()
  2868. def on_file_savedefaults(self):
  2869. """
  2870. Callback for menu item File->Save Defaults. Saves application default options
  2871. ``self.defaults`` to current_defaults.FlatConfig.
  2872. :return: None
  2873. """
  2874. self.preferencesUiManager.save_defaults()
  2875. def final_save(self):
  2876. """
  2877. Callback for doing a preferences save to file whenever the application is about to quit.
  2878. If the project has changes, it will ask the user to save the project.
  2879. :return: None
  2880. """
  2881. if self.save_in_progress:
  2882. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2883. return
  2884. if self.should_we_save and self.collection.get_list():
  2885. msgbox = QtWidgets.QMessageBox()
  2886. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2887. "\n"
  2888. "Do you want to Save the project?"))
  2889. msgbox.setWindowTitle(_("Save changes"))
  2890. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2891. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2892. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2893. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2894. msgbox.setDefaultButton(bt_yes)
  2895. msgbox.exec_()
  2896. response = msgbox.clickedButton()
  2897. if response == bt_yes:
  2898. try:
  2899. self.trayIcon.hide()
  2900. except Exception:
  2901. pass
  2902. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2903. elif response == bt_no:
  2904. try:
  2905. self.trayIcon.hide()
  2906. except Exception:
  2907. pass
  2908. self.quit_application()
  2909. elif response == bt_cancel:
  2910. return
  2911. else:
  2912. try:
  2913. self.trayIcon.hide()
  2914. except Exception:
  2915. pass
  2916. self.quit_application()
  2917. def quit_application(self):
  2918. """
  2919. Called (as a pyslot or not) when the application is quit.
  2920. :return: None
  2921. """
  2922. self.preferencesUiManager.save_defaults(silent=True)
  2923. log.debug("App.quit_application() --> App Defaults saved.")
  2924. if self.cmd_line_headless != 1:
  2925. # save app state to file
  2926. stgs = QSettings("Open Source", "FlatCAM")
  2927. stgs.setValue('saved_gui_state', self.ui.saveState())
  2928. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2929. stgs.setValue(
  2930. 'language',
  2931. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2932. )
  2933. stgs.setValue(
  2934. 'notebook_font_size',
  2935. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2936. )
  2937. stgs.setValue(
  2938. 'axis_font_size',
  2939. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2940. )
  2941. stgs.setValue(
  2942. 'textbox_font_size',
  2943. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2944. )
  2945. stgs.setValue(
  2946. 'hud_font_size',
  2947. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2948. )
  2949. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2950. stgs.setValue(
  2951. 'machinist',
  2952. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2953. )
  2954. # This will write the setting to the platform specific storage.
  2955. del stgs
  2956. log.debug("App.quit_application() --> App UI state saved.")
  2957. # try to quit the Socket opened by ArgsThread class
  2958. try:
  2959. self.new_launch.stop.emit()
  2960. except Exception as err:
  2961. log.debug("App.quit_application() --> %s" % str(err))
  2962. # try to quit the QThread that run ArgsThread class
  2963. try:
  2964. self.th.quit()
  2965. except Exception as e:
  2966. log.debug("App.quit_application() --> %s" % str(e))
  2967. # terminate workers
  2968. self.workers.__del__()
  2969. # quit app by signalling for self.kill_app() method
  2970. # self.close_app_signal.emit()
  2971. QtWidgets.qApp.quit()
  2972. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2973. # we use the following command
  2974. minor_v = sys.version_info.minor
  2975. if minor_v < 8:
  2976. sys.exit(0)
  2977. else:
  2978. os._exit(0) # fix to work with Python 3.8
  2979. @staticmethod
  2980. def kill_app():
  2981. QtWidgets.qApp.quit()
  2982. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2983. # we use the following command
  2984. sys.exit(0)
  2985. def on_portable_checked(self, state):
  2986. """
  2987. Callback called when the checkbox in Preferences GUI is checked.
  2988. It will set the application as portable by creating the preferences and recent files in the
  2989. 'config' folder found in the FlatCAM installation folder.
  2990. :param state: boolean, the state of the checkbox when clicked/checked
  2991. :return:
  2992. """
  2993. line_no = 0
  2994. data = None
  2995. if sys.platform != 'win32':
  2996. # this won't work in Linux or MacOS
  2997. return
  2998. # test if the app was frozen and choose the path for the configuration file
  2999. if getattr(sys, "frozen", False) is True:
  3000. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3001. else:
  3002. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3003. config_file = current_data_path + '\\configuration.txt'
  3004. try:
  3005. with open(config_file, 'r') as f:
  3006. try:
  3007. data = f.readlines()
  3008. except Exception as e:
  3009. log.debug('App.__init__() -->%s' % str(e))
  3010. return
  3011. except FileNotFoundError:
  3012. pass
  3013. for line in data:
  3014. line = line.strip('\n')
  3015. param = str(line).rpartition('=')
  3016. if param[0] == 'portable':
  3017. break
  3018. line_no += 1
  3019. if state:
  3020. data[line_no] = 'portable=True\n'
  3021. # create the new defauults files
  3022. # create current_defaults.FlatConfig file if there is none
  3023. try:
  3024. f = open(current_data_path + '/current_defaults.FlatConfig')
  3025. f.close()
  3026. except IOError:
  3027. App.log.debug('Creating empty current_defaults.FlatConfig')
  3028. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3029. json.dump({}, f)
  3030. f.close()
  3031. # create factory_defaults.FlatConfig file if there is none
  3032. try:
  3033. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3034. f.close()
  3035. except IOError:
  3036. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3037. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3038. json.dump({}, f)
  3039. f.close()
  3040. try:
  3041. f = open(current_data_path + '/recent.json')
  3042. f.close()
  3043. except IOError:
  3044. App.log.debug('Creating empty recent.json')
  3045. f = open(current_data_path + '/recent.json', 'w')
  3046. json.dump([], f)
  3047. f.close()
  3048. try:
  3049. fp = open(current_data_path + '/recent_projects.json')
  3050. fp.close()
  3051. except IOError:
  3052. App.log.debug('Creating empty recent_projects.json')
  3053. fp = open(current_data_path + '/recent_projects.json', 'w')
  3054. json.dump([], fp)
  3055. fp.close()
  3056. # save the current defaults to the new defaults file
  3057. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3058. else:
  3059. data[line_no] = 'portable=False\n'
  3060. with open(config_file, 'w') as f:
  3061. f.writelines(data)
  3062. def on_register_files(self, obj_type=None):
  3063. """
  3064. Called whenever there is a need to register file extensions with FlatCAM.
  3065. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3066. :param obj_type: the type of object to be register for.
  3067. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3068. :return: None
  3069. """
  3070. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3071. new_reg_path = 'Software\\Classes\\'
  3072. # find if the current user is admin
  3073. try:
  3074. is_admin = os.getuid() == 0
  3075. except AttributeError:
  3076. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3077. if is_admin is True:
  3078. root_path = winreg.HKEY_LOCAL_MACHINE
  3079. else:
  3080. root_path = winreg.HKEY_CURRENT_USER
  3081. # create the keys
  3082. def set_reg(name, root_pth, new_reg_path, value):
  3083. try:
  3084. winreg.CreateKey(root_pth, new_reg_path)
  3085. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3086. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3087. return True
  3088. except WindowsError:
  3089. return False
  3090. # delete key in registry
  3091. def delete_reg(root_pth, reg_path, key_to_del):
  3092. key_to_del_path = reg_path + key_to_del
  3093. try:
  3094. winreg.DeleteKey(root_pth, key_to_del_path)
  3095. return True
  3096. except WindowsError:
  3097. return False
  3098. if obj_type is None or obj_type == 'excellon':
  3099. exc_list = \
  3100. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3101. exc_list = [x for x in exc_list if x != '']
  3102. # register all keys in the Preferences window
  3103. for ext in exc_list:
  3104. new_k = new_reg_path + '.%s' % ext
  3105. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3106. # and unregister those that are no longer in the Preferences windows but are in the file
  3107. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3108. if ext not in exc_list:
  3109. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3110. # now write the updated extensions to the self.defaults
  3111. # new_ext = ''
  3112. # for ext in exc_list:
  3113. # new_ext = new_ext + ext + ', '
  3114. # self.defaults["fa_excellon"] = new_ext
  3115. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3116. if obj_type is None or obj_type == 'gcode':
  3117. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3118. gco_list = [x for x in gco_list if x != '']
  3119. # register all keys in the Preferences window
  3120. for ext in gco_list:
  3121. new_k = new_reg_path + '.%s' % ext
  3122. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3123. # and unregister those that are no longer in the Preferences windows but are in the file
  3124. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3125. if ext not in gco_list:
  3126. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3127. # now write the updated extensions to the self.defaults
  3128. # new_ext = ''
  3129. # for ext in gco_list:
  3130. # new_ext = new_ext + ext + ', '
  3131. # self.defaults["fa_gcode"] = new_ext
  3132. self.inform.emit('[success] %s' %
  3133. _("Selected GCode file extensions registered with FlatCAM."))
  3134. if obj_type is None or obj_type == 'gerber':
  3135. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3136. grb_list = [x for x in grb_list if x != '']
  3137. # register all keys in the Preferences window
  3138. for ext in grb_list:
  3139. new_k = new_reg_path + '.%s' % ext
  3140. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3141. # and unregister those that are no longer in the Preferences windows but are in the file
  3142. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3143. if ext not in grb_list:
  3144. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3145. # now write the updated extensions to the self.defaults
  3146. # new_ext = ''
  3147. # for ext in grb_list:
  3148. # new_ext = new_ext + ext + ', '
  3149. # self.defaults["fa_gerber"] = new_ext
  3150. self.inform.emit('[success] %s' %
  3151. _("Selected Gerber file extensions registered with FlatCAM."))
  3152. def add_extension(self, ext_type):
  3153. """
  3154. Add a file extension to the list for a specific object
  3155. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3156. :return:
  3157. """
  3158. if ext_type == 'excellon':
  3159. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3160. if new_ext == '':
  3161. return
  3162. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3163. if new_ext in old_val:
  3164. return
  3165. old_val.append(new_ext)
  3166. old_val.sort()
  3167. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3168. if ext_type == 'gcode':
  3169. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3170. if new_ext == '':
  3171. return
  3172. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3173. if new_ext in old_val:
  3174. return
  3175. old_val.append(new_ext)
  3176. old_val.sort()
  3177. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3178. if ext_type == 'gerber':
  3179. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3180. if new_ext == '':
  3181. return
  3182. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3183. if new_ext in old_val:
  3184. return
  3185. old_val.append(new_ext)
  3186. old_val.sort()
  3187. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3188. if ext_type == 'keyword':
  3189. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3190. if new_kw == '':
  3191. return
  3192. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3193. if new_kw in old_val:
  3194. return
  3195. old_val.append(new_kw)
  3196. old_val.sort()
  3197. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3198. # update the self.myKeywords so the model is updated
  3199. self.autocomplete_kw_list = \
  3200. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3201. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3202. self.shell._edit.set_model_data(self.myKeywords)
  3203. def del_extension(self, ext_type):
  3204. """
  3205. Remove a file extension from the list for a specific object
  3206. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3207. :return:
  3208. """
  3209. if ext_type == 'excellon':
  3210. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3211. if new_ext == '':
  3212. return
  3213. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3214. if new_ext not in old_val:
  3215. return
  3216. old_val.remove(new_ext)
  3217. old_val.sort()
  3218. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3219. if ext_type == 'gcode':
  3220. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3221. if new_ext == '':
  3222. return
  3223. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3224. if new_ext not in old_val:
  3225. return
  3226. old_val.remove(new_ext)
  3227. old_val.sort()
  3228. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3229. if ext_type == 'gerber':
  3230. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3231. if new_ext == '':
  3232. return
  3233. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3234. if new_ext not in old_val:
  3235. return
  3236. old_val.remove(new_ext)
  3237. old_val.sort()
  3238. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3239. if ext_type == 'keyword':
  3240. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3241. if new_kw == '':
  3242. return
  3243. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3244. if new_kw not in old_val:
  3245. return
  3246. old_val.remove(new_kw)
  3247. old_val.sort()
  3248. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3249. # update the self.myKeywords so the model is updated
  3250. self.autocomplete_kw_list = \
  3251. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3252. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3253. self.shell._edit.set_model_data(self.myKeywords)
  3254. def restore_extensions(self, ext_type):
  3255. """
  3256. Restore all file extensions associations with FlatCAM, for a specific object
  3257. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3258. :return:
  3259. """
  3260. if ext_type == 'excellon':
  3261. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3262. # for the ability to open Excellon files with .txt extension
  3263. new_exc_list = deepcopy(self.exc_list)
  3264. try:
  3265. new_exc_list.remove('txt')
  3266. except ValueError:
  3267. pass
  3268. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3269. if ext_type == 'gcode':
  3270. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3271. if ext_type == 'gerber':
  3272. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3273. if ext_type == 'keyword':
  3274. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3275. # update the self.myKeywords so the model is updated
  3276. self.autocomplete_kw_list = self.default_keywords
  3277. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3278. self.shell._edit.set_model_data(self.myKeywords)
  3279. def delete_all_extensions(self, ext_type):
  3280. """
  3281. Delete all file extensions associations with FlatCAM, for a specific object
  3282. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3283. :return:
  3284. """
  3285. if ext_type == 'excellon':
  3286. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3287. if ext_type == 'gcode':
  3288. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3289. if ext_type == 'gerber':
  3290. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3291. if ext_type == 'keyword':
  3292. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3293. # update the self.myKeywords so the model is updated
  3294. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3295. self.shell._edit.set_model_data(self.myKeywords)
  3296. def on_edit_join(self, name=None):
  3297. """
  3298. Callback for Edit->Join. Joins the selected geometry objects into
  3299. a new one.
  3300. :return: None
  3301. """
  3302. self.defaults.report_usage("on_edit_join()")
  3303. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3304. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3305. geo_type_set = set()
  3306. objs = self.collection.get_selected()
  3307. if len(objs) < 2:
  3308. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3309. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3310. return 'fail'
  3311. for obj in objs:
  3312. geo_type_set.add(obj.multigeo)
  3313. # if len(geo_type_list) == 1 means that all list elements are the same
  3314. if len(geo_type_set) != 1:
  3315. self.inform.emit('[ERROR] %s' %
  3316. _("Failed join. The Geometry objects are of different types.\n"
  3317. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3318. "convert from one to another and retry joining \n"
  3319. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3320. "the result may not be what was expected. \n"
  3321. "Check the generated GCODE."))
  3322. return
  3323. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3324. if True in geo_type_set:
  3325. def initialize(geo_obj, app):
  3326. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3327. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3328. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3329. for v in geo_obj.tools.values():
  3330. v['data']['name'] = obj_name_multi
  3331. self.new_object("geometry", obj_name_multi, initialize)
  3332. else:
  3333. def initialize(geo_obj, app):
  3334. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3335. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3336. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3337. for v in geo_obj.tools.values():
  3338. v['data']['name'] = obj_name_single
  3339. self.new_object("geometry", obj_name_single, initialize)
  3340. self.should_we_save = True
  3341. def on_edit_join_exc(self):
  3342. """
  3343. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3344. a new Excellon.
  3345. :return: None
  3346. """
  3347. self.defaults.report_usage("on_edit_join_exc()")
  3348. objs = self.collection.get_selected()
  3349. for obj in objs:
  3350. if not isinstance(obj, ExcellonObject):
  3351. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3352. return
  3353. if len(objs) < 2:
  3354. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3355. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3356. return 'fail'
  3357. def initialize(exc_obj, app):
  3358. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3359. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3360. self.new_object("excellon", 'Combo_Excellon', initialize)
  3361. self.should_we_save = True
  3362. def on_edit_join_grb(self):
  3363. """
  3364. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3365. a new Gerber object.
  3366. :return: None
  3367. """
  3368. self.defaults.report_usage("on_edit_join_grb()")
  3369. objs = self.collection.get_selected()
  3370. for obj in objs:
  3371. if not isinstance(obj, GerberObject):
  3372. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3373. return
  3374. if len(objs) < 2:
  3375. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3376. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3377. return 'fail'
  3378. def initialize(grb_obj, app):
  3379. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3380. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3381. self.new_object("gerber", 'Combo_Gerber', initialize)
  3382. self.should_we_save = True
  3383. def on_convert_singlegeo_to_multigeo(self):
  3384. """
  3385. Called for converting a Geometry object from single-geo to multi-geo.
  3386. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3387. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3388. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3389. the solid-geometry of that tool.
  3390. :return: None
  3391. """
  3392. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3393. obj = self.collection.get_active()
  3394. if obj is None:
  3395. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3396. return
  3397. if not isinstance(obj, GeometryObject):
  3398. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3399. return
  3400. obj.multigeo = True
  3401. for tooluid, dict_value in obj.tools.items():
  3402. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3403. if not isinstance(obj.solid_geometry, list):
  3404. obj.solid_geometry = [obj.solid_geometry]
  3405. # obj.solid_geometry[:] = []
  3406. obj.plot()
  3407. self.should_we_save = True
  3408. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3409. def on_convert_multigeo_to_singlegeo(self):
  3410. """
  3411. Called for converting a Geometry object from multi-geo to single-geo.
  3412. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3413. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3414. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3415. the solid-geometry of that tool.
  3416. :return: None
  3417. """
  3418. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3419. obj = self.collection.get_active()
  3420. if obj is None:
  3421. self.inform.emit('[ERROR_NOTCL] %s' %
  3422. _("Failed. Select a Geometry Object and try again."))
  3423. return
  3424. if not isinstance(obj, GeometryObject):
  3425. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3426. (_("Expected a GeometryObject, got"), type(obj)))
  3427. return
  3428. obj.multigeo = False
  3429. total_solid_geometry = []
  3430. for tooluid, dict_value in obj.tools.items():
  3431. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3432. # clear the original geometry
  3433. dict_value['solid_geometry'][:] = []
  3434. obj.solid_geometry = deepcopy(total_solid_geometry)
  3435. obj.plot()
  3436. self.should_we_save = True
  3437. self.inform.emit('[success] %s' %
  3438. _("A Geometry object was converted to SingleGeo type."))
  3439. def on_defaults_dict_change(self, field):
  3440. """
  3441. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3442. Edit -> Preferences tab window.
  3443. :param field: the key of the self.defaults dictionary that was changed.
  3444. :return: None
  3445. """
  3446. self.preferencesUiManager.defaults_write_form_field(field=field)
  3447. if field == "units":
  3448. self.set_screen_units(self.defaults['units'])
  3449. def set_screen_units(self, units):
  3450. """
  3451. Set the FlatCAM units on the status bar.
  3452. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3453. :return: None
  3454. """
  3455. self.ui.units_label.setText("[" + units.lower() + "]")
  3456. def on_toggle_units_click(self):
  3457. try:
  3458. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3459. except (TypeError, AttributeError):
  3460. pass
  3461. if self.defaults["units"] == 'MM':
  3462. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3463. else:
  3464. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3465. self.on_toggle_units(no_pref=True)
  3466. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3467. lambda: self.on_toggle_units(no_pref=False))
  3468. def on_toggle_units(self, no_pref=False):
  3469. """
  3470. Callback for the Units radio-button change in the Preferences tab.
  3471. Changes the application's default units adn for the project too.
  3472. If changing the project's units, the change propagates to all of
  3473. the objects in the project.
  3474. :return: None
  3475. """
  3476. self.defaults.report_usage("on_toggle_units")
  3477. if self.toggle_units_ignore:
  3478. return
  3479. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3480. # If option is the same, then ignore
  3481. if new_units == self.defaults["units"].upper():
  3482. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3483. return
  3484. # Keys in self.defaults for which to scale their values
  3485. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3486. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3487. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3488. "gerber_editor_ma_high",
  3489. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3490. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3491. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3492. "excellon_feedrate_probe", "excellon_milling_dia",
  3493. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3494. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3495. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3496. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3497. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3498. "geometry_extracut_length", "geometry_z_pdepth",
  3499. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3500. 'cncjob_tooldia',
  3501. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3502. "tools_paintnewdia",
  3503. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3504. "tools_nccnewdia", "tools_ncc_offset_value",
  3505. "tools_2sided_drilldia",
  3506. "tools_film_boundary", "tools_film_scale_stroke",
  3507. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3508. "tools_cutout_depthperpass",
  3509. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3510. "tools_panelize_spacing_rows",
  3511. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3512. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3513. "tools_transform_buffer_dis",
  3514. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3515. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3516. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3517. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3518. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3519. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3520. "tools_cr_h2h_val", "tools_cr_dh_val",
  3521. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3522. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3523. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3524. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3525. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3526. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3527. "tools_copper_thieving_mask_clearance",
  3528. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3529. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3530. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3531. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3532. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3533. "tools_invert_margin",
  3534. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3535. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3536. def scale_defaults(sfactor):
  3537. for dim in dimensions:
  3538. if dim in [
  3539. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3540. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3541. 'tools_transform_mirror_point'
  3542. ]:
  3543. if self.defaults[dim] is None or self.defaults[dim] == '':
  3544. continue
  3545. try:
  3546. coordinates = self.defaults[dim].split(",")
  3547. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3548. coords_xy[0] *= sfactor
  3549. coords_xy[1] *= sfactor
  3550. self.defaults[dim] = "%.*f, %.*f" % (
  3551. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3552. except Exception as e:
  3553. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3554. elif dim in [
  3555. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3556. ]:
  3557. if self.defaults[dim] is None or self.defaults[dim] == '':
  3558. continue
  3559. try:
  3560. self.defaults[dim] = float(self.defaults[dim])
  3561. tools_diameters = [self.defaults[dim]]
  3562. except ValueError:
  3563. try:
  3564. tools_string = self.defaults[dim].split(",")
  3565. tools_diameters = [eval(a) for a in tools_string if a != '']
  3566. except Exception as e:
  3567. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3568. continue
  3569. self.defaults[dim] = ''
  3570. td_len = len(tools_diameters)
  3571. if td_len > 1:
  3572. for t in range(td_len):
  3573. tools_diameters[t] *= sfactor
  3574. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3575. else:
  3576. tools_diameters[0] *= sfactor
  3577. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3578. elif dim in ['global_gridx', 'global_gridy']:
  3579. # format the number of decimals to the one specified in self.decimals
  3580. try:
  3581. val = float(self.defaults[dim]) * sfactor
  3582. except Exception as e:
  3583. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3584. continue
  3585. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3586. else:
  3587. # the number of decimals for the rest is kept unchanged
  3588. if self.defaults[dim]:
  3589. try:
  3590. val = float(self.defaults[dim]) * sfactor
  3591. except Exception as e:
  3592. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3593. continue
  3594. self.defaults[dim] = val
  3595. # The scaling factor depending on choice of units.
  3596. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3597. # Changing project units. Warn user.
  3598. msgbox = QtWidgets.QMessageBox()
  3599. msgbox.setWindowTitle(_("Toggle Units"))
  3600. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3601. msgbox.setText(_("Changing the units of the project\n"
  3602. "will scale all objects.\n\n"
  3603. "Do you want to continue?"))
  3604. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3605. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3606. msgbox.setDefaultButton(bt_ok)
  3607. msgbox.exec_()
  3608. response = msgbox.clickedButton()
  3609. if response == bt_ok:
  3610. if no_pref is False:
  3611. self.preferencesUiManager.defaults_read_form()
  3612. scale_defaults(factor)
  3613. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3614. self.defaults["units"] = new_units
  3615. # update the defaults from form, some may assume that the conversion is enough and it's not
  3616. self.on_options_app2project()
  3617. # update the objects
  3618. for obj in self.collection.get_list():
  3619. obj.convert_units(new_units)
  3620. # make that the properties stored in the object are also updated
  3621. self.object_changed.emit(obj)
  3622. # rebuild the object UI
  3623. obj.build_ui()
  3624. # change this only if the workspace is active
  3625. if self.defaults['global_workspace'] is True:
  3626. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3627. # adjust the grid values on the main toolbar
  3628. val_x = float(self.defaults['global_gridx']) * factor
  3629. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3630. current = self.collection.get_active()
  3631. if current is not None:
  3632. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3633. if not isinstance(current, GeometryObject):
  3634. current.to_form()
  3635. # replot all objects
  3636. self.plot_all()
  3637. # set the status labels to reflect the current FlatCAM units
  3638. self.set_screen_units(new_units)
  3639. # signal to the app that we changed the object properties and it should save the project
  3640. self.should_we_save = True
  3641. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3642. else:
  3643. # Undo toggling
  3644. self.toggle_units_ignore = True
  3645. if self.defaults['units'].upper() == 'MM':
  3646. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3647. else:
  3648. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3649. self.toggle_units_ignore = False
  3650. # store the grid values so they are not changed in the next step
  3651. val_x = float(self.defaults['global_gridx'])
  3652. val_y = float(self.defaults['global_gridy'])
  3653. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3654. self.preferencesUiManager.defaults_read_form()
  3655. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3656. # in self.defaults from the GUI elements but
  3657. # I don't want it for the grid values, so I update them here
  3658. self.defaults['global_gridx'] = val_x
  3659. self.defaults['global_gridy'] = val_y
  3660. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3661. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3662. def on_fullscreen(self, disable=False):
  3663. self.defaults.report_usage("on_fullscreen()")
  3664. flags = self.ui.windowFlags()
  3665. if self.toggle_fscreen is False and disable is False:
  3666. # self.ui.showFullScreen()
  3667. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3668. a = self.ui.geometry()
  3669. self.x_pos = a.x()
  3670. self.y_pos = a.y()
  3671. self.width = a.width()
  3672. self.height = a.height()
  3673. # set new geometry to full desktop rect
  3674. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3675. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3676. # everything else will not work without this hack. This happen in Windows.
  3677. # https://bugreports.qt.io/browse/QTBUG-41309
  3678. desktop = QtWidgets.QApplication.desktop()
  3679. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3680. rec = desktop.screenGeometry(screen)
  3681. x = rec.x() - 1
  3682. y = rec.y() - 1
  3683. h = rec.height() + 2
  3684. w = rec.width() + 2
  3685. self.ui.setGeometry(x, y, w, h)
  3686. self.ui.show()
  3687. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3688. tb.setVisible(False)
  3689. self.ui.snap_toolbar.setVisible(True) # This is always visible
  3690. # self.ui.splitter_left.setVisible(False)
  3691. self.ui.splitter.setSizes([0, 1])
  3692. self.toggle_fscreen = True
  3693. elif self.toggle_fscreen is True or disable is True:
  3694. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3695. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3696. self.ui.showNormal()
  3697. self.restore_toolbar_view()
  3698. # self.ui.splitter_left.setVisible(True)
  3699. self.toggle_fscreen = False
  3700. def on_toggle_plotarea(self):
  3701. self.defaults.report_usage("on_toggle_plotarea()")
  3702. try:
  3703. name = self.ui.plot_tab_area.widget(0).objectName()
  3704. except AttributeError:
  3705. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3706. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3707. self.ui.plot_tab_area.protectTab(0)
  3708. return
  3709. if name != 'plotarea_tab':
  3710. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3711. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3712. self.ui.plot_tab_area.protectTab(0)
  3713. else:
  3714. self.ui.plot_tab_area.closeTab(0)
  3715. def on_toggle_notebook(self):
  3716. if self.ui.splitter.sizes()[0] == 0:
  3717. self.ui.splitter.setSizes([1, 1])
  3718. self.ui.menu_toggle_nb.setChecked(True)
  3719. else:
  3720. self.ui.splitter.setSizes([0, 1])
  3721. self.ui.menu_toggle_nb.setChecked(False)
  3722. def on_toggle_axis(self):
  3723. self.defaults.report_usage("on_toggle_axis()")
  3724. if self.toggle_axis is False:
  3725. if self.is_legacy is False:
  3726. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3727. parent=self.plotcanvas.view.scene)
  3728. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3729. parent=self.plotcanvas.view.scene)
  3730. else:
  3731. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3732. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3733. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3734. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3735. self.plotcanvas.canvas.draw()
  3736. self.toggle_axis = True
  3737. else:
  3738. if self.is_legacy is False:
  3739. self.plotcanvas.v_line.parent = None
  3740. self.plotcanvas.h_line.parent = None
  3741. else:
  3742. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3743. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3744. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3745. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3746. self.plotcanvas.canvas.draw()
  3747. self.toggle_axis = False
  3748. def on_toggle_hud(self):
  3749. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3750. def on_toggle_grid(self):
  3751. self.defaults.report_usage("on_toggle_grid()")
  3752. self.ui.grid_snap_btn.trigger()
  3753. def on_toggle_grid_lines(self):
  3754. self.defaults.report_usage("on_toggle_grd_lines()")
  3755. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3756. if tt_settings.contains("theme"):
  3757. theme = tt_settings.value('theme', type=str)
  3758. else:
  3759. theme = 'white'
  3760. if self.toggle_grid_lines is False:
  3761. if self.is_legacy is False:
  3762. if theme == 'white':
  3763. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3764. else:
  3765. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3766. else:
  3767. self.plotcanvas.axes.grid(True)
  3768. try:
  3769. self.plotcanvas.canvas.draw()
  3770. except IndexError:
  3771. pass
  3772. pass
  3773. self.toggle_grid_lines = True
  3774. else:
  3775. if self.is_legacy is False:
  3776. if theme == 'white':
  3777. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3778. else:
  3779. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3780. else:
  3781. self.plotcanvas.axes.grid(False)
  3782. try:
  3783. self.plotcanvas.canvas.draw()
  3784. except IndexError:
  3785. pass
  3786. self.toggle_grid_lines = False
  3787. if self.is_legacy is False:
  3788. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3789. # - perhaps is a bug in VisPy implementation
  3790. if self.grid_status():
  3791. self.app_cursor.enabled = False
  3792. self.app_cursor.enabled = True
  3793. else:
  3794. self.app_cursor.enabled = True
  3795. self.app_cursor.enabled = False
  3796. def on_update_exc_export(self, state):
  3797. """
  3798. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3799. if the update_excellon_cb checkbox is checked
  3800. :param state: state of the checkbox whose signals is tied to his slot
  3801. :return:
  3802. """
  3803. if state:
  3804. # first try to disconnect
  3805. try:
  3806. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3807. disconnect(self.on_excellon_format_changed)
  3808. except TypeError:
  3809. pass
  3810. try:
  3811. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3812. disconnect(self.on_excellon_format_changed)
  3813. except TypeError:
  3814. pass
  3815. try:
  3816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3817. disconnect(self.on_excellon_format_changed)
  3818. except TypeError:
  3819. pass
  3820. try:
  3821. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3822. disconnect(self.on_excellon_format_changed)
  3823. except TypeError:
  3824. pass
  3825. try:
  3826. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3827. disconnect(self.on_excellon_zeros_changed)
  3828. except TypeError:
  3829. pass
  3830. try:
  3831. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3832. disconnect(self.on_excellon_zeros_changed)
  3833. except TypeError:
  3834. pass
  3835. # the connect them
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3837. self.on_excellon_format_changed)
  3838. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3839. self.on_excellon_format_changed)
  3840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3841. self.on_excellon_format_changed)
  3842. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3843. self.on_excellon_format_changed)
  3844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3845. self.on_excellon_zeros_changed)
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3847. self.on_excellon_units_changed)
  3848. else:
  3849. # disconnect the signals
  3850. try:
  3851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3852. disconnect(self.on_excellon_format_changed)
  3853. except TypeError:
  3854. pass
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3857. disconnect(self.on_excellon_format_changed)
  3858. except TypeError:
  3859. pass
  3860. try:
  3861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3862. disconnect(self.on_excellon_format_changed)
  3863. except TypeError:
  3864. pass
  3865. try:
  3866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3867. disconnect(self.on_excellon_format_changed)
  3868. except TypeError:
  3869. pass
  3870. try:
  3871. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3872. disconnect(self.on_excellon_zeros_changed)
  3873. except TypeError:
  3874. pass
  3875. try:
  3876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3877. disconnect(self.on_excellon_zeros_changed)
  3878. except TypeError:
  3879. pass
  3880. def on_excellon_format_changed(self):
  3881. """
  3882. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3883. :return: None
  3884. """
  3885. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3886. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3887. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3888. )
  3889. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3890. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3891. )
  3892. else:
  3893. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3894. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3895. )
  3896. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3897. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3898. )
  3899. def on_excellon_zeros_changed(self):
  3900. """
  3901. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3902. :return: None
  3903. """
  3904. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3905. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3906. )
  3907. def on_excellon_units_changed(self):
  3908. """
  3909. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3910. :return: None
  3911. """
  3912. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3913. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3914. )
  3915. self.on_excellon_format_changed()
  3916. def on_film_color_entry(self):
  3917. self.defaults['tools_film_color'] = \
  3918. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3919. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3920. "background-color:%s;"
  3921. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3922. )
  3923. def on_film_color_button(self):
  3924. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3925. c_dialog = QtWidgets.QColorDialog()
  3926. film_color = c_dialog.getColor(initial=current_color)
  3927. if film_color.isValid() is False:
  3928. return
  3929. # if new color is different then mark that the Preferences are changed
  3930. if film_color != current_color:
  3931. self.preferencesUiManager.on_preferences_edited()
  3932. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3933. "background-color:%s;"
  3934. "border-color: dimgray" % str(film_color.name())
  3935. )
  3936. new_val_sel = str(film_color.name())
  3937. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3938. self.defaults['tools_film_color'] = new_val_sel
  3939. def on_qrcode_fill_color_entry(self):
  3940. self.defaults['tools_qrcode_fill_color'] = \
  3941. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3942. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3943. "background-color:%s;"
  3944. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3945. )
  3946. def on_qrcode_fill_color_button(self):
  3947. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3948. c_dialog = QtWidgets.QColorDialog()
  3949. fill_color = c_dialog.getColor(initial=current_color)
  3950. if fill_color.isValid() is False:
  3951. return
  3952. # if new color is different then mark that the Preferences are changed
  3953. if fill_color != current_color:
  3954. self.preferencesUiManager.on_preferences_edited()
  3955. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3956. "background-color:%s;"
  3957. "border-color: dimgray" % str(fill_color.name())
  3958. )
  3959. new_val_sel = str(fill_color.name())
  3960. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3961. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3962. def on_qrcode_back_color_entry(self):
  3963. self.defaults['tools_qrcode_back_color'] = \
  3964. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3965. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3966. "background-color:%s;"
  3967. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3968. )
  3969. def on_qrcode_back_color_button(self):
  3970. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3971. c_dialog = QtWidgets.QColorDialog()
  3972. back_color = c_dialog.getColor(initial=current_color)
  3973. if back_color.isValid() is False:
  3974. return
  3975. # if new color is different then mark that the Preferences are changed
  3976. if back_color != current_color:
  3977. self.preferencesUiManager.on_preferences_edited()
  3978. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3979. "background-color:%s;"
  3980. "border-color: dimgray" % str(back_color.name())
  3981. )
  3982. new_val_sel = str(back_color.name())
  3983. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3984. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3985. def on_tab_rmb_click(self, checked):
  3986. self.ui.notebook.set_detachable(val=checked)
  3987. self.defaults["global_tabs_detachable"] = checked
  3988. self.ui.plot_tab_area.set_detachable(val=checked)
  3989. self.defaults["global_tabs_detachable"] = checked
  3990. def on_tab_setup_context_menu(self):
  3991. initial_checked = self.defaults["global_tabs_detachable"]
  3992. action_name = str(_("Detachable Tabs"))
  3993. action = QtWidgets.QAction(self)
  3994. action.setCheckable(True)
  3995. action.setText(action_name)
  3996. action.setChecked(initial_checked)
  3997. self.ui.notebook.tabBar.addAction(action)
  3998. self.ui.plot_tab_area.tabBar.addAction(action)
  3999. try:
  4000. action.triggered.disconnect()
  4001. except TypeError:
  4002. pass
  4003. action.triggered.connect(self.on_tab_rmb_click)
  4004. def on_deselect_all(self):
  4005. self.collection.set_all_inactive()
  4006. self.delete_selection_shape()
  4007. def on_workspace_modified(self):
  4008. # self.save_defaults(silent=True)
  4009. self.plotcanvas.delete_workspace()
  4010. self.preferencesUiManager.defaults_read_form()
  4011. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4012. def on_workspace(self):
  4013. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4014. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4015. else:
  4016. self.plotcanvas.delete_workspace()
  4017. self.preferencesUiManager.defaults_read_form()
  4018. # self.save_defaults(silent=True)
  4019. def on_workspace_toggle(self):
  4020. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4021. try:
  4022. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4023. except TypeError:
  4024. pass
  4025. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4026. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4027. self.on_workspace()
  4028. def on_cursor_type(self, val):
  4029. """
  4030. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4031. :return: None
  4032. """
  4033. self.app_cursor.enabled = False
  4034. if val == 'small':
  4035. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4036. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4037. self.app_cursor = self.plotcanvas.new_cursor()
  4038. else:
  4039. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4040. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4041. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4042. if self.ui.grid_snap_btn.isChecked():
  4043. self.app_cursor.enabled = True
  4044. else:
  4045. self.app_cursor.enabled = False
  4046. def on_tool_add_keypress(self):
  4047. # ## Current application units in Upper Case
  4048. self.units = self.defaults['units'].upper()
  4049. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4050. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4051. if notebook_widget_name == 'selected_tab':
  4052. if self.collection.get_active().kind == 'geometry':
  4053. # Tool add works for Geometry only if Advanced is True in Preferences
  4054. if self.defaults["global_app_level"] == 'a':
  4055. tool_add_popup = FCInputDialog(title="New Tool ...",
  4056. text='Enter a Tool Diameter:',
  4057. min=0.0000, max=99.9999, decimals=4)
  4058. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4059. val, ok = tool_add_popup.get_value()
  4060. if ok:
  4061. if float(val) == 0:
  4062. self.inform.emit('[WARNING_NOTCL] %s' %
  4063. _("Please enter a tool diameter with non-zero value, in Float format."))
  4064. return
  4065. self.collection.get_active().on_tool_add(dia=float(val))
  4066. else:
  4067. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4068. else:
  4069. msgbox = QtWidgets.QMessageBox()
  4070. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4071. "Go to Preferences -> General - Show Advanced Options."))
  4072. msgbox.setWindowTitle("Tool adding ...")
  4073. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4074. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4075. msgbox.setDefaultButton(bt_ok)
  4076. msgbox.exec_()
  4077. # work only if the notebook tab on focus is the Tools_Tab
  4078. if notebook_widget_name == 'tool_tab':
  4079. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4080. # and only if the tool is NCC Tool
  4081. if tool_widget == self.ncclear_tool.toolName:
  4082. self.ncclear_tool.on_add_tool_by_key()
  4083. # and only if the tool is Paint Area Tool
  4084. elif tool_widget == self.paint_tool.toolName:
  4085. self.paint_tool.on_add_tool_by_key()
  4086. # and only if the tool is Solder Paste Dispensing Tool
  4087. elif tool_widget == self.paste_tool.toolName:
  4088. self.paste_tool.on_add_tool_by_key()
  4089. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4090. # See description below.
  4091. def on_delete_keypress(self):
  4092. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4093. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4094. if notebook_widget_name == 'selected_tab':
  4095. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4096. self.collection.get_active().on_tool_delete()
  4097. # work only if the notebook tab on focus is the Tools_Tab
  4098. elif notebook_widget_name == 'tool_tab':
  4099. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4100. # and only if the tool is NCC Tool
  4101. if tool_widget == self.ncclear_tool.toolName:
  4102. self.ncclear_tool.on_tool_delete()
  4103. # and only if the tool is Paint Tool
  4104. elif tool_widget == self.paint_tool.toolName:
  4105. self.paint_tool.on_tool_delete()
  4106. # and only if the tool is Solder Paste Dispensing Tool
  4107. elif tool_widget == self.paste_tool.toolName:
  4108. self.paste_tool.on_tool_delete()
  4109. else:
  4110. self.on_delete()
  4111. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4112. # some screens you have to be careful where you hover with your mouse.
  4113. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4114. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4115. # Complicated, I know :)
  4116. def on_delete(self, force_deletion=False):
  4117. """
  4118. Delete the currently selected FlatCAMObjs.
  4119. :param force_deletion: used by Tcl command
  4120. :return: None
  4121. """
  4122. self.defaults.report_usage("on_delete()")
  4123. response = None
  4124. bt_ok = None
  4125. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4126. # a geometry object before we update it.
  4127. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4128. and self.grb_editor.editor_active is False:
  4129. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4130. msgbox = QtWidgets.QMessageBox()
  4131. msgbox.setWindowTitle(_("Delete objects"))
  4132. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4133. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4134. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4135. "the selected objects?"))
  4136. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4137. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4138. msgbox.setDefaultButton(bt_ok)
  4139. msgbox.exec_()
  4140. response = msgbox.clickedButton()
  4141. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4142. response = bt_ok
  4143. if response == bt_ok:
  4144. if self.collection.get_active():
  4145. self.log.debug("App.on_delete()")
  4146. for obj_active in self.collection.get_selected():
  4147. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4148. if obj_active.kind == 'gerber':
  4149. for el in obj_active.mark_shapes:
  4150. obj_active.mark_shapes[el].clear(update=True)
  4151. obj_active.mark_shapes[el].enabled = False
  4152. # obj_active.mark_shapes[el] = None
  4153. del el
  4154. elif isinstance(obj_active, CNCJobObject):
  4155. try:
  4156. obj_active.text_col.enabled = False
  4157. del obj_active.text_col
  4158. obj_active.annotation.clear(update=True)
  4159. del obj_active.annotation
  4160. except AttributeError as e:
  4161. log.debug(
  4162. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4163. )
  4164. while self.collection.get_selected():
  4165. self.delete_first_selected()
  4166. self.inform.emit('%s...' % _("Object(s) deleted"))
  4167. # make sure that the selection shape is deleted, too
  4168. self.delete_selection_shape()
  4169. # if there are no longer objects delete also the exclusion areas shapes
  4170. if not self.collection.get_list():
  4171. self.exc_areas.clear_shapes()
  4172. else:
  4173. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4174. else:
  4175. self.inform.emit(_("Save the work in Editor and try again ..."))
  4176. def delete_first_selected(self):
  4177. # Keep this for later
  4178. try:
  4179. sel_obj = self.collection.get_active()
  4180. name = sel_obj.options["name"]
  4181. isPlotted = sel_obj.options["plot"]
  4182. except AttributeError:
  4183. self.log.debug("Nothing selected for deletion")
  4184. return
  4185. if self.is_legacy is True:
  4186. # Remove plot only if the object was plotted otherwise delaxes will fail
  4187. if isPlotted:
  4188. try:
  4189. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4190. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4191. except Exception as e:
  4192. log.debug("App.delete_first_selected() --> %s" % str(e))
  4193. self.plotcanvas.auto_adjust_axes()
  4194. # Remove from dictionary
  4195. self.collection.delete_active()
  4196. # Clear form
  4197. self.setup_component_editor()
  4198. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4199. def on_set_origin(self):
  4200. """
  4201. Set the origin to the left mouse click position
  4202. :return: None
  4203. """
  4204. # display the message for the user
  4205. # and ask him to click on the desired position
  4206. self.defaults.report_usage("on_set_origin()")
  4207. def origin_replot():
  4208. def worker_task():
  4209. with self.proc_container.new('%s...' % _("Plotting")):
  4210. for obj in self.collection.get_list():
  4211. obj.plot()
  4212. self.plotcanvas.fit_view()
  4213. if self.is_legacy:
  4214. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4215. else:
  4216. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4217. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4218. self.inform.emit(_('Click to set the origin ...'))
  4219. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4220. # first disconnect it as it may have been used by something else
  4221. try:
  4222. self.replot_signal.disconnect()
  4223. except TypeError:
  4224. pass
  4225. self.replot_signal[list].connect(origin_replot)
  4226. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4227. """
  4228. :param event:
  4229. :param location:
  4230. :param noplot:
  4231. :param use_thread:
  4232. :return:
  4233. """
  4234. noplot_sig = noplot
  4235. def worker_task():
  4236. with self.proc_container.new(_("Setting Origin...")):
  4237. obj_list = self.collection.get_list()
  4238. for obj in obj_list:
  4239. obj.offset((x, y))
  4240. self.object_changed.emit(obj)
  4241. # Update the object bounding box options
  4242. a, b, c, d = obj.bounds()
  4243. obj.options['xmin'] = a
  4244. obj.options['ymin'] = b
  4245. obj.options['xmax'] = c
  4246. obj.options['ymax'] = d
  4247. self.inform.emit('[success] %s...' % _('Origin set'))
  4248. for obj in obj_list:
  4249. out_name = obj.options["name"]
  4250. if obj.kind == 'gerber':
  4251. obj.source_file = self.export_gerber(
  4252. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4253. elif obj.kind == 'excellon':
  4254. obj.source_file = self.export_excellon(
  4255. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4256. if noplot_sig is False:
  4257. self.replot_signal.emit([])
  4258. if location is not None:
  4259. if len(location) != 2:
  4260. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4261. return 'fail'
  4262. x, y = location
  4263. if use_thread is True:
  4264. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4265. else:
  4266. worker_task()
  4267. self.should_we_save = True
  4268. return
  4269. if event.button == 1:
  4270. if self.is_legacy is False:
  4271. event_pos = event.pos
  4272. else:
  4273. event_pos = (event.xdata, event.ydata)
  4274. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4275. if self.grid_status():
  4276. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4277. else:
  4278. pos = pos_canvas
  4279. x = 0 - pos[0]
  4280. y = 0 - pos[1]
  4281. if use_thread is True:
  4282. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4283. else:
  4284. worker_task()
  4285. self.should_we_save = True
  4286. def on_move2origin(self, use_thread=True):
  4287. """
  4288. Move selected objects to origin.
  4289. :param use_thread: Control if to use threaded operation. Boolean.
  4290. :return:
  4291. """
  4292. def worker_task():
  4293. with self.proc_container.new(_("Moving to Origin...")):
  4294. obj_list = self.collection.get_selected()
  4295. if not obj_list:
  4296. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4297. return
  4298. xminlist = []
  4299. yminlist = []
  4300. # first get a bounding box to fit all
  4301. for obj in obj_list:
  4302. xmin, ymin, xmax, ymax = obj.bounds()
  4303. xminlist.append(xmin)
  4304. yminlist.append(ymin)
  4305. # get the minimum x,y for all objects selected
  4306. x = min(xminlist)
  4307. y = min(yminlist)
  4308. for obj in obj_list:
  4309. obj.offset((-x, -y))
  4310. self.object_changed.emit(obj)
  4311. # Update the object bounding box options
  4312. a, b, c, d = obj.bounds()
  4313. obj.options['xmin'] = a
  4314. obj.options['ymin'] = b
  4315. obj.options['xmax'] = c
  4316. obj.options['ymax'] = d
  4317. for obj in obj_list:
  4318. obj.plot()
  4319. for obj in obj_list:
  4320. out_name = obj.options["name"]
  4321. if obj.kind == 'gerber':
  4322. obj.source_file = self.export_gerber(
  4323. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4324. elif obj.kind == 'excellon':
  4325. obj.source_file = self.export_excellon(
  4326. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4327. self.inform.emit('[success] %s...' % _('Origin set'))
  4328. if use_thread is True:
  4329. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4330. else:
  4331. worker_task()
  4332. self.should_we_save = True
  4333. def on_jump_to(self, custom_location=None, fit_center=True):
  4334. """
  4335. Jump to a location by setting the mouse cursor location.
  4336. :param custom_location: Jump to a specified point. (x, y) tuple.
  4337. :param fit_center: If to fit view. Boolean.
  4338. :return:
  4339. """
  4340. self.defaults.report_usage("on_jump_to()")
  4341. if not custom_location:
  4342. dia_box_location = None
  4343. try:
  4344. dia_box_location = eval(self.clipboard.text())
  4345. except Exception:
  4346. pass
  4347. if type(dia_box_location) == tuple:
  4348. dia_box_location = str(dia_box_location)
  4349. else:
  4350. dia_box_location = None
  4351. # dia_box = Dialog_box(title=_("Jump to ..."),
  4352. # label=_("Enter the coordinates in format X,Y:"),
  4353. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4354. # initial_text=dia_box_location)
  4355. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4356. label=_("Enter the coordinates in format X,Y:"),
  4357. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4358. initial_text=dia_box_location,
  4359. reference=self.defaults['global_jump_ref'])
  4360. if dia_box.ok is True:
  4361. try:
  4362. location = eval(dia_box.location)
  4363. if not isinstance(location, tuple):
  4364. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4365. return
  4366. if dia_box.reference == 'rel':
  4367. rel_x = self.mouse[0] + location[0]
  4368. rel_y = self.mouse[1] + location[1]
  4369. location = (rel_x, rel_y)
  4370. self.defaults['global_jump_ref'] = dia_box.reference
  4371. except Exception:
  4372. return
  4373. else:
  4374. return
  4375. else:
  4376. location = custom_location
  4377. self.jump_signal.emit(location)
  4378. if fit_center:
  4379. self.plotcanvas.fit_center(loc=location)
  4380. cursor = QtGui.QCursor()
  4381. if self.is_legacy is False:
  4382. # I don't know where those differences come from but they are constant for the current
  4383. # execution of the application and they are multiples of a value around 0.0263mm.
  4384. # In a random way sometimes they are more sometimes they are less
  4385. # if units == 'MM':
  4386. # cal_factor = 0.0263
  4387. # else:
  4388. # cal_factor = 0.0263 / 25.4
  4389. cal_location = (location[0], location[1])
  4390. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4391. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4392. j_pos = (
  4393. int(canvas_origin.x() + round(jump_loc[0])),
  4394. int(canvas_origin.y() + round(jump_loc[1]))
  4395. )
  4396. cursor.setPos(j_pos[0], j_pos[1])
  4397. else:
  4398. # find the canvas origin which is in the top left corner
  4399. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4400. # determine the coordinates for the lowest left point of the canvas
  4401. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4402. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4403. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4404. # canvas) and the point (width, height) is in the top-right location
  4405. loc = self.plotcanvas.axes.transData.transform_point(location)
  4406. j_pos = (
  4407. int(x0 + loc[0]),
  4408. int(y0 - loc[1])
  4409. )
  4410. cursor.setPos(j_pos[0], j_pos[1])
  4411. self.plotcanvas.mouse = [location[0], location[1]]
  4412. if self.defaults["global_cursor_color_enabled"] is True:
  4413. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4414. else:
  4415. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4416. if self.grid_status():
  4417. # Update cursor
  4418. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4419. symbol='++', edge_color=self.cursor_color_3D,
  4420. edge_width=self.defaults["global_cursor_width"],
  4421. size=self.defaults["global_cursor_size"])
  4422. # Set the relative position label
  4423. dx = location[0] - float(self.rel_point1[0])
  4424. dy = location[1] - float(self.rel_point1[1])
  4425. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4426. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4427. # # Set the position label
  4428. #
  4429. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4430. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4431. units = self.defaults["units"].lower()
  4432. self.plotcanvas.text_hud.text = \
  4433. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4434. dx, units, dy, units, location[0], units, location[1], units)
  4435. self.inform.emit('[success] %s' % _("Done."))
  4436. return location
  4437. def on_locate(self, obj, fit_center=True):
  4438. """
  4439. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4440. :param obj: The object on which to locate certain points
  4441. :param fit_center: If to fit view. Boolean.
  4442. :return: A point location. (x, y) tuple.
  4443. """
  4444. self.defaults.report_usage("on_locate()")
  4445. if obj is None:
  4446. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4447. return 'fail'
  4448. class DialogBoxChoice(QtWidgets.QDialog):
  4449. def __init__(self, title=None, icon=None, choice='bl'):
  4450. """
  4451. :param title: string with the window title
  4452. """
  4453. super(DialogBoxChoice, self).__init__()
  4454. self.ok = False
  4455. self.setWindowIcon(icon)
  4456. self.setWindowTitle(str(title))
  4457. self.form = QtWidgets.QFormLayout(self)
  4458. self.ref_radio = RadioSet([
  4459. {"label": _("Bottom-Left"), "value": "bl"},
  4460. {"label": _("Top-Left"), "value": "tl"},
  4461. {"label": _("Bottom-Right"), "value": "br"},
  4462. {"label": _("Top-Right"), "value": "tr"},
  4463. {"label": _("Center"), "value": "c"}
  4464. ], orientation='vertical', stretch=False)
  4465. self.ref_radio.set_value(choice)
  4466. self.form.addRow(self.ref_radio)
  4467. self.button_box = QtWidgets.QDialogButtonBox(
  4468. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4469. Qt.Horizontal, parent=self)
  4470. self.form.addRow(self.button_box)
  4471. self.button_box.accepted.connect(self.accept)
  4472. self.button_box.rejected.connect(self.reject)
  4473. if self.exec_() == QtWidgets.QDialog.Accepted:
  4474. self.ok = True
  4475. self.location_point = self.ref_radio.get_value()
  4476. else:
  4477. self.ok = False
  4478. self.location_point = None
  4479. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4480. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4481. choice=self.defaults['global_locate_pt'])
  4482. if dia_box.ok is True:
  4483. try:
  4484. location_point = dia_box.location_point
  4485. self.defaults['global_locate_pt'] = dia_box.location_point
  4486. except Exception:
  4487. return
  4488. else:
  4489. return
  4490. loc_b = obj.bounds()
  4491. if location_point == 'bl':
  4492. location = (loc_b[0], loc_b[1])
  4493. elif location_point == 'tl':
  4494. location = (loc_b[0], loc_b[3])
  4495. elif location_point == 'br':
  4496. location = (loc_b[2], loc_b[1])
  4497. elif location_point == 'tr':
  4498. location = (loc_b[2], loc_b[3])
  4499. else:
  4500. # center
  4501. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4502. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4503. location = (cx, cy)
  4504. self.locate_signal.emit(location, location_point)
  4505. if fit_center:
  4506. self.plotcanvas.fit_center(loc=location)
  4507. cursor = QtGui.QCursor()
  4508. if self.is_legacy is False:
  4509. # I don't know where those differences come from but they are constant for the current
  4510. # execution of the application and they are multiples of a value around 0.0263mm.
  4511. # In a random way sometimes they are more sometimes they are less
  4512. # if units == 'MM':
  4513. # cal_factor = 0.0263
  4514. # else:
  4515. # cal_factor = 0.0263 / 25.4
  4516. cal_location = (location[0], location[1])
  4517. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4518. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4519. j_pos = (
  4520. int(canvas_origin.x() + round(jump_loc[0])),
  4521. int(canvas_origin.y() + round(jump_loc[1]))
  4522. )
  4523. cursor.setPos(j_pos[0], j_pos[1])
  4524. else:
  4525. # find the canvas origin which is in the top left corner
  4526. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4527. # determine the coordinates for the lowest left point of the canvas
  4528. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4529. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4530. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4531. # canvas) and the point (width, height) is in the top-right location
  4532. loc = self.plotcanvas.axes.transData.transform_point(location)
  4533. j_pos = (
  4534. int(x0 + loc[0]),
  4535. int(y0 - loc[1])
  4536. )
  4537. cursor.setPos(j_pos[0], j_pos[1])
  4538. self.plotcanvas.mouse = [location[0], location[1]]
  4539. if self.defaults["global_cursor_color_enabled"] is True:
  4540. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4541. else:
  4542. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4543. if self.grid_status():
  4544. # Update cursor
  4545. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4546. symbol='++', edge_color=self.cursor_color_3D,
  4547. edge_width=self.defaults["global_cursor_width"],
  4548. size=self.defaults["global_cursor_size"])
  4549. # Set the relative position label
  4550. self.dx = location[0] - float(self.rel_point1[0])
  4551. self.dy = location[1] - float(self.rel_point1[1])
  4552. # Set the position label
  4553. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4554. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4555. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4556. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4557. units = self.defaults["units"].lower()
  4558. self.plotcanvas.text_hud.text = \
  4559. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4560. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4561. self.inform.emit('[success] %s' % _("Done."))
  4562. return location
  4563. def on_copy_command(self):
  4564. """
  4565. Will copy a selection of objects, creating new objects.
  4566. :return:
  4567. """
  4568. self.defaults.report_usage("on_copy_command()")
  4569. def initialize(obj_init, app):
  4570. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4571. try:
  4572. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4573. except AttributeError:
  4574. pass
  4575. try:
  4576. obj_init.apertures = deepcopy(obj.apertures)
  4577. except AttributeError:
  4578. pass
  4579. try:
  4580. if obj.tools:
  4581. obj_init.tools = deepcopy(obj.tools)
  4582. except Exception as err:
  4583. log.debug("App.on_copy_command() --> %s" % str(err))
  4584. try:
  4585. obj_init.source_file = deepcopy(obj.source_file)
  4586. except (AttributeError, TypeError):
  4587. pass
  4588. def initialize_excellon(obj_init, app):
  4589. obj_init.source_file = deepcopy(obj.source_file)
  4590. obj_init.tools = deepcopy(obj.tools)
  4591. # drills are offset, so they need to be deep copied
  4592. obj_init.drills = deepcopy(obj.drills)
  4593. # slots are offset, so they need to be deep copied
  4594. obj_init.slots = deepcopy(obj.slots)
  4595. obj_init.create_geometry()
  4596. def initialize_script(obj_init, app_obj):
  4597. obj_init.source_file = deepcopy(obj.source_file)
  4598. def initialize_document(obj_init, app_obj):
  4599. obj_init.source_file = deepcopy(obj.source_file)
  4600. for obj in self.collection.get_selected():
  4601. obj_name = obj.options["name"]
  4602. try:
  4603. if isinstance(obj, ExcellonObject):
  4604. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4605. elif isinstance(obj, GerberObject):
  4606. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4607. elif isinstance(obj, GeometryObject):
  4608. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4609. elif isinstance(obj, ScriptObject):
  4610. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4611. elif isinstance(obj, DocumentObject):
  4612. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4613. except Exception as e:
  4614. return "Operation failed: %s" % str(e)
  4615. def on_copy_object2(self, custom_name):
  4616. def initialize_geometry(obj_init, app):
  4617. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4618. try:
  4619. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4620. except AttributeError:
  4621. pass
  4622. try:
  4623. obj_init.apertures = deepcopy(obj.apertures)
  4624. except AttributeError:
  4625. pass
  4626. try:
  4627. if obj.tools:
  4628. obj_init.tools = deepcopy(obj.tools)
  4629. except Exception as ee:
  4630. log.debug("on_copy_object2() --> %s" % str(ee))
  4631. def initialize_gerber(obj_init, app):
  4632. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4633. obj_init.apertures = deepcopy(obj.apertures)
  4634. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4635. def initialize_excellon(obj_init, app):
  4636. obj_init.tools = deepcopy(obj.tools)
  4637. # drills are offset, so they need to be deep copied
  4638. obj_init.drills = deepcopy(obj.drills)
  4639. # slots are offset, so they need to be deep copied
  4640. obj_init.slots = deepcopy(obj.slots)
  4641. obj_init.create_geometry()
  4642. for obj in self.collection.get_selected():
  4643. obj_name = obj.options["name"]
  4644. try:
  4645. if isinstance(obj, ExcellonObject):
  4646. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4647. elif isinstance(obj, GerberObject):
  4648. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4649. elif isinstance(obj, GeometryObject):
  4650. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4651. except Exception as er:
  4652. return "Operation failed: %s" % str(er)
  4653. def on_rename_object(self, text):
  4654. """
  4655. Will rename an object.
  4656. :param text: New name for the object.
  4657. :return:
  4658. """
  4659. self.defaults.report_usage("on_rename_object()")
  4660. named_obj = self.collection.get_active()
  4661. for obj in named_obj:
  4662. if obj is list:
  4663. self.on_rename_object(text)
  4664. else:
  4665. try:
  4666. obj.options['name'] = text
  4667. except Exception as e:
  4668. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4669. def convert_any2geo(self):
  4670. """
  4671. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4672. :return:
  4673. """
  4674. self.defaults.report_usage("convert_any2geo()")
  4675. def initialize(obj_init, app):
  4676. obj_init.solid_geometry = obj.solid_geometry
  4677. try:
  4678. obj_init.follow_geometry = obj.follow_geometry
  4679. except AttributeError:
  4680. pass
  4681. try:
  4682. obj_init.apertures = obj.apertures
  4683. except AttributeError:
  4684. pass
  4685. try:
  4686. if obj.tools:
  4687. obj_init.tools = obj.tools
  4688. except AttributeError:
  4689. pass
  4690. def initialize_excellon(obj_init, app):
  4691. # objs = self.collection.get_selected()
  4692. # GeometryObject.merge(objs, obj)
  4693. solid_geo = []
  4694. for tool in obj.tools:
  4695. for geo in obj.tools[tool]['solid_geometry']:
  4696. solid_geo.append(geo)
  4697. obj_init.solid_geometry = deepcopy(solid_geo)
  4698. if not self.collection.get_selected():
  4699. log.warning("App.convert_any2geo --> No object selected")
  4700. self.inform.emit('[WARNING_NOTCL] %s' %
  4701. _("No object is selected. Select an object and try again."))
  4702. return
  4703. for obj in self.collection.get_selected():
  4704. obj_name = obj.options["name"]
  4705. try:
  4706. if isinstance(obj, ExcellonObject):
  4707. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4708. else:
  4709. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4710. except Exception as e:
  4711. return "Operation failed: %s" % str(e)
  4712. def convert_any2gerber(self):
  4713. """
  4714. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4715. :return:
  4716. """
  4717. self.defaults.report_usage("convert_any2gerber()")
  4718. def initialize_geometry(obj_init, app):
  4719. apertures = {}
  4720. apid = 0
  4721. apertures[str(apid)] = {}
  4722. apertures[str(apid)]['geometry'] = []
  4723. for obj_orig in obj.solid_geometry:
  4724. new_elem = {}
  4725. new_elem['solid'] = obj_orig
  4726. try:
  4727. new_elem['follow'] = obj_orig.exterior
  4728. except AttributeError:
  4729. pass
  4730. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4731. apertures[str(apid)]['size'] = 0.0
  4732. apertures[str(apid)]['type'] = 'C'
  4733. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4734. obj_init.apertures = deepcopy(apertures)
  4735. def initialize_excellon(obj_init, app):
  4736. apertures = {}
  4737. apid = 10
  4738. for tool in obj.tools:
  4739. apertures[str(apid)] = {}
  4740. apertures[str(apid)]['geometry'] = []
  4741. for geo in obj.tools[tool]['solid_geometry']:
  4742. new_el = {}
  4743. new_el['solid'] = geo
  4744. new_el['follow'] = geo.exterior
  4745. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4746. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4747. apertures[str(apid)]['type'] = 'C'
  4748. apid += 1
  4749. # create solid_geometry
  4750. solid_geometry = []
  4751. for apid in apertures:
  4752. for geo_el in apertures[apid]['geometry']:
  4753. solid_geometry.append(geo_el['solid'])
  4754. solid_geometry = MultiPolygon(solid_geometry)
  4755. solid_geometry = solid_geometry.buffer(0.0000001)
  4756. obj_init.solid_geometry = deepcopy(solid_geometry)
  4757. obj_init.apertures = deepcopy(apertures)
  4758. # clear the working objects (perhaps not necessary due of Python GC)
  4759. apertures.clear()
  4760. if not self.collection.get_selected():
  4761. log.warning("App.convert_any2gerber --> No object selected")
  4762. self.inform.emit('[WARNING_NOTCL] %s' %
  4763. _("No object is selected. Select an object and try again."))
  4764. return
  4765. for obj in self.collection.get_selected():
  4766. obj_name = obj.options["name"]
  4767. try:
  4768. if isinstance(obj, ExcellonObject):
  4769. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4770. elif isinstance(obj, GeometryObject):
  4771. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4772. else:
  4773. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4774. except Exception as e:
  4775. return "Operation failed: %s" % str(e)
  4776. def abort_all_tasks(self):
  4777. """
  4778. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4779. on the first possible occasion.
  4780. :return:
  4781. """
  4782. if self.abort_flag is False:
  4783. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4784. self.abort_flag = True
  4785. self.cleanup.emit()
  4786. def app_is_idle(self):
  4787. if self.abort_flag:
  4788. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4789. self.abort_flag = False
  4790. def on_selectall(self):
  4791. """
  4792. Will draw a selection box shape around the selected objects.
  4793. :return:
  4794. """
  4795. self.defaults.report_usage("on_selectall()")
  4796. # delete the possible selection box around a possible selected object
  4797. self.delete_selection_shape()
  4798. for name in self.collection.get_names():
  4799. self.collection.set_active(name)
  4800. curr_sel_obj = self.collection.get_by_name(name)
  4801. # create the selection box around the selected object
  4802. if self.defaults['global_selection_shape'] is True:
  4803. self.draw_selection_shape(curr_sel_obj)
  4804. def on_preferences(self):
  4805. """
  4806. Adds the Preferences in a Tab in Plot Area
  4807. :return:
  4808. """
  4809. # add the tab if it was closed
  4810. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4811. # delete the absolute and relative position and messages in the infobar
  4812. self.ui.position_label.setText("")
  4813. # self.ui.rel_position_label.setText("")
  4814. # Switch plot_area to preferences page
  4815. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4816. # self.ui.show()
  4817. # detect changes in the preferences
  4818. for idx in range(self.ui.pref_tab_area.count()):
  4819. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4820. try:
  4821. try:
  4822. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4823. except (TypeError, AttributeError):
  4824. pass
  4825. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4826. except AttributeError:
  4827. pass
  4828. try:
  4829. try:
  4830. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4831. except (TypeError, AttributeError):
  4832. pass
  4833. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4834. except AttributeError:
  4835. pass
  4836. try:
  4837. try:
  4838. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4839. except (TypeError, AttributeError):
  4840. pass
  4841. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4842. except AttributeError:
  4843. pass
  4844. try:
  4845. try:
  4846. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4847. except (TypeError, AttributeError):
  4848. pass
  4849. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4850. except AttributeError:
  4851. pass
  4852. try:
  4853. try:
  4854. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4855. except (TypeError, AttributeError):
  4856. pass
  4857. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4858. except AttributeError:
  4859. pass
  4860. def on_tools_database(self, source='app'):
  4861. """
  4862. Adds the Tools Database in a Tab in Plot Area.
  4863. :return:
  4864. """
  4865. for idx in range(self.ui.plot_tab_area.count()):
  4866. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4867. # there can be only one instance of Tools Database at one time
  4868. return
  4869. if source == 'app':
  4870. self.tools_db_tab = ToolsDB2(
  4871. app=self,
  4872. parent=self.ui,
  4873. callback_on_edited=self.on_tools_db_edited,
  4874. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4875. )
  4876. elif source == 'ncc':
  4877. self.tools_db_tab = ToolsDB2(
  4878. app=self,
  4879. parent=self.ui,
  4880. callback_on_edited=self.on_tools_db_edited,
  4881. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4882. )
  4883. elif source == 'paint':
  4884. self.tools_db_tab = ToolsDB2(
  4885. app=self,
  4886. parent=self.ui,
  4887. callback_on_edited=self.on_tools_db_edited,
  4888. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4889. )
  4890. # add the tab if it was closed
  4891. try:
  4892. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4893. self.tools_db_tab.setObjectName("database_tab")
  4894. except Exception as e:
  4895. log.debug("App.on_tools_database() --> %s" % str(e))
  4896. return
  4897. # delete the absolute and relative position and messages in the infobar
  4898. self.ui.position_label.setText("")
  4899. # self.ui.rel_position_label.setText("")
  4900. # Switch plot_area to preferences page
  4901. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4902. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4903. self.tools_db_tab.ui_connect()
  4904. def on_tools_db_edited(self):
  4905. """
  4906. Executed whenever a tool is edited in Tools Database.
  4907. Will color the text of the Tools Database tab to Red color.
  4908. :return:
  4909. """
  4910. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4911. for idx in range(self.ui.plot_tab_area.count()):
  4912. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4913. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4914. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4915. self.tools_db_changed_flag = True
  4916. def on_geometry_tool_add_from_db_executed(self, tool):
  4917. """
  4918. Here add the tool from DB in the selected geometry object.
  4919. :return:
  4920. """
  4921. tool_from_db = deepcopy(tool)
  4922. obj = self.collection.get_active()
  4923. if isinstance(obj, GeometryObject):
  4924. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4925. # close the tab and delete it
  4926. for idx in range(self.ui.plot_tab_area.count()):
  4927. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4928. wdg = self.ui.plot_tab_area.widget(idx)
  4929. wdg.deleteLater()
  4930. self.ui.plot_tab_area.removeTab(idx)
  4931. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4932. else:
  4933. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4934. def on_plot_area_tab_closed(self, tab_obj_name):
  4935. """
  4936. Executed whenever a QTab is closed in the Plot Area.
  4937. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4938. :return:
  4939. """
  4940. if tab_obj_name == "preferences_tab":
  4941. self.preferencesUiManager.on_close_preferences_tab()
  4942. elif tab_obj_name == "database_tab":
  4943. # disconnect the signals from the table widget in tab
  4944. self.tools_db_tab.ui_disconnect()
  4945. if self.tools_db_changed_flag is True:
  4946. msgbox = QtWidgets.QMessageBox()
  4947. msgbox.setText(_("One or more Tools are edited.\n"
  4948. "Do you want to update the Tools Database?"))
  4949. msgbox.setWindowTitle(_("Save Tools Database"))
  4950. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4951. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4952. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4953. msgbox.setDefaultButton(bt_yes)
  4954. msgbox.exec_()
  4955. response = msgbox.clickedButton()
  4956. if response == bt_yes:
  4957. self.tools_db_tab.on_save_tools_db()
  4958. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4959. else:
  4960. self.tools_db_changed_flag = False
  4961. self.inform.emit('')
  4962. return
  4963. self.tools_db_tab.deleteLater()
  4964. elif tab_obj_name == "text_editor_tab":
  4965. self.toggle_codeeditor = False
  4966. elif tab_obj_name == "bookmarks_tab":
  4967. self.book_dialog_tab.rebuild_actions()
  4968. self.book_dialog_tab.deleteLater()
  4969. else:
  4970. return
  4971. # def on_plotarea_tab_closed(self, tab_idx):
  4972. # """
  4973. #
  4974. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4975. # :return:
  4976. # """
  4977. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4978. #
  4979. # if widget is not None:
  4980. # widget.deleteLater()
  4981. # self.ui.plot_tab_area.removeTab(tab_idx)
  4982. def on_flipy(self):
  4983. """
  4984. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4985. :return:
  4986. """
  4987. self.defaults.report_usage("on_flipy()")
  4988. obj_list = self.collection.get_selected()
  4989. xminlist = []
  4990. yminlist = []
  4991. xmaxlist = []
  4992. ymaxlist = []
  4993. if not obj_list:
  4994. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4995. else:
  4996. try:
  4997. # first get a bounding box to fit all
  4998. for obj in obj_list:
  4999. xmin, ymin, xmax, ymax = obj.bounds()
  5000. xminlist.append(xmin)
  5001. yminlist.append(ymin)
  5002. xmaxlist.append(xmax)
  5003. ymaxlist.append(ymax)
  5004. # get the minimum x,y and maximum x,y for all objects selected
  5005. xminimal = min(xminlist)
  5006. yminimal = min(yminlist)
  5007. xmaximal = max(xmaxlist)
  5008. ymaximal = max(ymaxlist)
  5009. px = 0.5 * (xminimal + xmaximal)
  5010. py = 0.5 * (yminimal + ymaximal)
  5011. # execute mirroring
  5012. for obj in obj_list:
  5013. obj.mirror('X', [px, py])
  5014. obj.plot()
  5015. self.object_changed.emit(obj)
  5016. self.inform.emit('[success] %s' %
  5017. _("Flip on Y axis done."))
  5018. except Exception as e:
  5019. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5020. return
  5021. def on_flipx(self):
  5022. """
  5023. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5024. :return:
  5025. """
  5026. self.defaults.report_usage("on_flipx()")
  5027. obj_list = self.collection.get_selected()
  5028. xminlist = []
  5029. yminlist = []
  5030. xmaxlist = []
  5031. ymaxlist = []
  5032. if not obj_list:
  5033. self.inform.emit('[WARNING_NOTCL] %s' %
  5034. _("No object selected to Flip on X axis."))
  5035. else:
  5036. try:
  5037. # first get a bounding box to fit all
  5038. for obj in obj_list:
  5039. xmin, ymin, xmax, ymax = obj.bounds()
  5040. xminlist.append(xmin)
  5041. yminlist.append(ymin)
  5042. xmaxlist.append(xmax)
  5043. ymaxlist.append(ymax)
  5044. # get the minimum x,y and maximum x,y for all objects selected
  5045. xminimal = min(xminlist)
  5046. yminimal = min(yminlist)
  5047. xmaximal = max(xmaxlist)
  5048. ymaximal = max(ymaxlist)
  5049. px = 0.5 * (xminimal + xmaximal)
  5050. py = 0.5 * (yminimal + ymaximal)
  5051. # execute mirroring
  5052. for obj in obj_list:
  5053. obj.mirror('Y', [px, py])
  5054. obj.plot()
  5055. self.object_changed.emit(obj)
  5056. self.inform.emit('[success] %s' %
  5057. _("Flip on X axis done."))
  5058. except Exception as e:
  5059. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5060. return
  5061. def on_rotate(self, silent=False, preset=None):
  5062. """
  5063. Executed when Options -> Rotate Selection menu entry is clicked.
  5064. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5065. :param preset: A value to be used as predefined angle for rotation.
  5066. :return:
  5067. """
  5068. self.defaults.report_usage("on_rotate()")
  5069. obj_list = self.collection.get_selected()
  5070. xminlist = []
  5071. yminlist = []
  5072. xmaxlist = []
  5073. ymaxlist = []
  5074. if not obj_list:
  5075. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5076. else:
  5077. if silent is False:
  5078. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5079. min=-360, max=360, decimals=4,
  5080. init_val=float(self.defaults['tools_transform_rotate']))
  5081. num, ok = rotatebox.get_value()
  5082. else:
  5083. num = preset
  5084. ok = True
  5085. if ok:
  5086. try:
  5087. # first get a bounding box to fit all
  5088. for obj in obj_list:
  5089. xmin, ymin, xmax, ymax = obj.bounds()
  5090. xminlist.append(xmin)
  5091. yminlist.append(ymin)
  5092. xmaxlist.append(xmax)
  5093. ymaxlist.append(ymax)
  5094. # get the minimum x,y and maximum x,y for all objects selected
  5095. xminimal = min(xminlist)
  5096. yminimal = min(yminlist)
  5097. xmaximal = max(xmaxlist)
  5098. ymaximal = max(ymaxlist)
  5099. px = 0.5 * (xminimal + xmaximal)
  5100. py = 0.5 * (yminimal + ymaximal)
  5101. for sel_obj in obj_list:
  5102. sel_obj.rotate(-float(num), point=(px, py))
  5103. sel_obj.plot()
  5104. self.object_changed.emit(sel_obj)
  5105. self.inform.emit('[success] %s' %
  5106. _("Rotation done."))
  5107. except Exception as e:
  5108. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5109. return
  5110. def on_skewx(self):
  5111. """
  5112. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5113. :return:
  5114. """
  5115. self.defaults.report_usage("on_skewx()")
  5116. obj_list = self.collection.get_selected()
  5117. xminlist = []
  5118. yminlist = []
  5119. if not obj_list:
  5120. self.inform.emit('[WARNING_NOTCL] %s' %
  5121. _("No object selected to Skew/Shear on X axis."))
  5122. else:
  5123. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5124. min=-360, max=360, decimals=4,
  5125. init_val=float(self.defaults['tools_transform_skew_x']))
  5126. num, ok = skewxbox.get_value()
  5127. if ok:
  5128. # first get a bounding box to fit all
  5129. for obj in obj_list:
  5130. xmin, ymin, xmax, ymax = obj.bounds()
  5131. xminlist.append(xmin)
  5132. yminlist.append(ymin)
  5133. # get the minimum x,y and maximum x,y for all objects selected
  5134. xminimal = min(xminlist)
  5135. yminimal = min(yminlist)
  5136. for obj in obj_list:
  5137. obj.skew(num, 0, point=(xminimal, yminimal))
  5138. obj.plot()
  5139. self.object_changed.emit(obj)
  5140. self.inform.emit('[success] %s' %
  5141. _("Skew on X axis done."))
  5142. def on_skewy(self):
  5143. """
  5144. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5145. :return:
  5146. """
  5147. self.defaults.report_usage("on_skewy()")
  5148. obj_list = self.collection.get_selected()
  5149. xminlist = []
  5150. yminlist = []
  5151. if not obj_list:
  5152. self.inform.emit('[WARNING_NOTCL] %s' %
  5153. _("No object selected to Skew/Shear on Y axis."))
  5154. else:
  5155. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5156. min=-360, max=360, decimals=4,
  5157. init_val=float(self.defaults['tools_transform_skew_y']))
  5158. num, ok = skewybox.get_value()
  5159. if ok:
  5160. # first get a bounding box to fit all
  5161. for obj in obj_list:
  5162. xmin, ymin, xmax, ymax = obj.bounds()
  5163. xminlist.append(xmin)
  5164. yminlist.append(ymin)
  5165. # get the minimum x,y and maximum x,y for all objects selected
  5166. xminimal = min(xminlist)
  5167. yminimal = min(yminlist)
  5168. for obj in obj_list:
  5169. obj.skew(0, num, point=(xminimal, yminimal))
  5170. obj.plot()
  5171. self.object_changed.emit(obj)
  5172. self.inform.emit('[success] %s' %
  5173. _("Skew on Y axis done."))
  5174. def on_plots_updated(self):
  5175. """
  5176. Callback used to report when the plots have changed.
  5177. Adjust axes and zooms to fit.
  5178. :return: None
  5179. """
  5180. if self.is_legacy is False:
  5181. self.plotcanvas.update()
  5182. else:
  5183. self.plotcanvas.auto_adjust_axes()
  5184. self.on_zoom_fit(None)
  5185. self.collection.update_view()
  5186. # self.inform.emit(_("Plots updated ..."))
  5187. def on_toolbar_replot(self):
  5188. """
  5189. Callback for toolbar button. Re-plots all objects.
  5190. :return: None
  5191. """
  5192. self.defaults.report_usage("on_toolbar_replot")
  5193. self.log.debug("on_toolbar_replot()")
  5194. try:
  5195. self.collection.get_active().read_form()
  5196. except AttributeError:
  5197. self.log.debug("on_toolbar_replot(): AttributeError")
  5198. pass
  5199. self.plot_all()
  5200. def on_row_activated(self, index):
  5201. if index.isValid():
  5202. if index.internalPointer().parent_item != self.collection.root_item:
  5203. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5204. self.collection.on_item_activated(index)
  5205. def on_row_selected(self, obj_name):
  5206. """
  5207. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5208. It mean we clicked outside of the items and deselected all
  5209. :param obj_name:
  5210. :return:
  5211. """
  5212. if obj_name == 'none':
  5213. for act in self.ui.menuobjects.actions():
  5214. act.setChecked(False)
  5215. return
  5216. # get the name of the selected objects and add them to a list
  5217. name_list = []
  5218. for obj in self.collection.get_selected():
  5219. name_list.append(obj.options['name'])
  5220. # set all actions as unchecked but the ones selected make them checked
  5221. for act in self.ui.menuobjects.actions():
  5222. act.setChecked(False)
  5223. if act.text() in name_list:
  5224. act.setChecked(True)
  5225. def on_collection_updated(self, obj, state, old_name):
  5226. """
  5227. Create a menu from the object loaded in the collection.
  5228. :param obj: object that was changed (added, deleted, renamed)
  5229. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5230. :param old_name: the old name of the object before the action that triggered this slot happened
  5231. :return: None
  5232. """
  5233. icon_files = {
  5234. "gerber": self.resource_location + "/flatcam_icon16.png",
  5235. "excellon": self.resource_location + "/drill16.png",
  5236. "cncjob": self.resource_location + "/cnc16.png",
  5237. "geometry": self.resource_location + "/geometry16.png",
  5238. "script": self.resource_location + "/script_new16.png",
  5239. "document": self.resource_location + "/notes16_1.png"
  5240. }
  5241. if state == 'append':
  5242. for act in self.ui.menuobjects.actions():
  5243. try:
  5244. act.triggered.disconnect()
  5245. except TypeError:
  5246. pass
  5247. self.ui.menuobjects.clear()
  5248. gerber_list = []
  5249. exc_list = []
  5250. cncjob_list = []
  5251. geo_list = []
  5252. script_list = []
  5253. doc_list = []
  5254. for name in self.collection.get_names():
  5255. obj_named = self.collection.get_by_name(name)
  5256. if obj_named.kind == 'gerber':
  5257. gerber_list.append(name)
  5258. elif obj_named.kind == 'excellon':
  5259. exc_list.append(name)
  5260. elif obj_named.kind == 'cncjob':
  5261. cncjob_list.append(name)
  5262. elif obj_named.kind == 'geometry':
  5263. geo_list.append(name)
  5264. elif obj_named.kind == 'script':
  5265. script_list.append(name)
  5266. elif obj_named.kind == 'document':
  5267. doc_list.append(name)
  5268. def add_act(o_name):
  5269. obj_for_icon = self.collection.get_by_name(o_name)
  5270. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5271. add_action.setCheckable(True)
  5272. add_action.setText(o_name)
  5273. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5274. add_action.triggered.connect(
  5275. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5276. self.collection.set_inactive(o_name))
  5277. self.ui.menuobjects.addAction(add_action)
  5278. for name in gerber_list:
  5279. add_act(name)
  5280. self.ui.menuobjects.addSeparator()
  5281. for name in exc_list:
  5282. add_act(name)
  5283. self.ui.menuobjects.addSeparator()
  5284. for name in cncjob_list:
  5285. add_act(name)
  5286. self.ui.menuobjects.addSeparator()
  5287. for name in geo_list:
  5288. add_act(name)
  5289. self.ui.menuobjects.addSeparator()
  5290. for name in script_list:
  5291. add_act(name)
  5292. self.ui.menuobjects.addSeparator()
  5293. for name in doc_list:
  5294. add_act(name)
  5295. self.ui.menuobjects.addSeparator()
  5296. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5297. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5298. _('Select All')
  5299. )
  5300. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5301. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5302. _('Deselect All')
  5303. )
  5304. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5305. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5306. elif state == 'delete':
  5307. for act in self.ui.menuobjects.actions():
  5308. if act.text() == obj.options['name']:
  5309. try:
  5310. act.triggered.disconnect()
  5311. except TypeError:
  5312. pass
  5313. self.ui.menuobjects.removeAction(act)
  5314. break
  5315. elif state == 'rename':
  5316. for act in self.ui.menuobjects.actions():
  5317. if act.text() == old_name:
  5318. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5319. add_action.setText(obj.options['name'])
  5320. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5321. add_action.triggered.connect(
  5322. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5323. self.collection.set_inactive(obj.options['name']))
  5324. self.ui.menuobjects.insertAction(act, add_action)
  5325. try:
  5326. act.triggered.disconnect()
  5327. except TypeError:
  5328. pass
  5329. self.ui.menuobjects.removeAction(act)
  5330. break
  5331. elif state == 'delete_all':
  5332. for act in self.ui.menuobjects.actions():
  5333. try:
  5334. act.triggered.disconnect()
  5335. except TypeError:
  5336. pass
  5337. self.ui.menuobjects.clear()
  5338. self.ui.menuobjects.addSeparator()
  5339. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5340. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5341. _('Select All')
  5342. )
  5343. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5344. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5345. _('Deselect All')
  5346. )
  5347. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5348. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5349. def on_objects_selection(self, on_off):
  5350. obj_list = self.collection.get_names()
  5351. if on_off is True:
  5352. self.collection.set_all_active()
  5353. for act in self.ui.menuobjects.actions():
  5354. try:
  5355. act.setChecked(True)
  5356. except Exception:
  5357. pass
  5358. if obj_list:
  5359. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5360. else:
  5361. self.collection.set_all_inactive()
  5362. for act in self.ui.menuobjects.actions():
  5363. try:
  5364. act.setChecked(False)
  5365. except Exception:
  5366. pass
  5367. if obj_list:
  5368. self.inform.emit('%s' % _("Objects selection is cleared."))
  5369. else:
  5370. self.inform.emit('')
  5371. def grid_status(self):
  5372. return True if self.ui.grid_snap_btn.isChecked() else False
  5373. def populate_cmenu_grids(self):
  5374. units = self.defaults['units'].lower()
  5375. # for act in self.ui.cmenu_gridmenu.actions():
  5376. # act.triggered.disconnect()
  5377. self.ui.cmenu_gridmenu.clear()
  5378. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5379. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5380. _("Grid On/Off"))
  5381. grid_toggle.setCheckable(True)
  5382. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5383. self.ui.cmenu_gridmenu.addSeparator()
  5384. for grid in sorted_list:
  5385. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5386. "%s" % str(grid))
  5387. action.triggered.connect(self.set_grid)
  5388. self.ui.cmenu_gridmenu.addSeparator()
  5389. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5390. _("Add"))
  5391. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5392. _("Delete"))
  5393. grid_add.triggered.connect(self.on_grid_add)
  5394. grid_delete.triggered.connect(self.on_grid_delete)
  5395. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5396. def set_grid(self):
  5397. menu_action = self.sender()
  5398. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5399. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5400. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5401. def on_grid_add(self):
  5402. # ## Current application units in lower Case
  5403. units = self.defaults['units'].lower()
  5404. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5405. text=_('Enter a Grid Value:'),
  5406. min=0.0000, max=99.9999, decimals=4)
  5407. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5408. val, ok = grid_add_popup.get_value()
  5409. if ok:
  5410. if float(val) == 0:
  5411. self.inform.emit('[WARNING_NOTCL] %s' %
  5412. _("Please enter a grid value with non-zero value, in Float format."))
  5413. return
  5414. else:
  5415. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5416. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5417. self.inform.emit('[success] %s...' % _("New Grid added"))
  5418. else:
  5419. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5420. else:
  5421. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5422. def on_grid_delete(self):
  5423. # ## Current application units in lower Case
  5424. units = self.defaults['units'].lower()
  5425. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5426. text='Enter a Grid Value:',
  5427. min=0.0000, max=99.9999, decimals=4)
  5428. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5429. val, ok = grid_del_popup.get_value()
  5430. if ok:
  5431. if float(val) == 0:
  5432. self.inform.emit('[WARNING_NOTCL] %s' %
  5433. _("Please enter a grid value with non-zero value, in Float format."))
  5434. return
  5435. else:
  5436. try:
  5437. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5438. except ValueError:
  5439. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5440. return
  5441. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5442. else:
  5443. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5444. def on_shortcut_list(self):
  5445. self.defaults.report_usage("on_shortcut_list()")
  5446. # add the tab if it was closed
  5447. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5448. # delete the absolute and relative position and messages in the infobar
  5449. self.ui.position_label.setText("")
  5450. # self.ui.rel_position_label.setText("")
  5451. # Switch plot_area to preferences page
  5452. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5453. # self.ui.show()
  5454. def on_select_tab(self, name):
  5455. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5456. if self.ui.splitter.sizes()[0] == 0:
  5457. self.ui.splitter.setSizes([1, 1])
  5458. else:
  5459. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5460. self.ui.splitter.setSizes([0, 1])
  5461. if name == 'project':
  5462. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5463. elif name == 'selected':
  5464. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5465. elif name == 'tool':
  5466. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5467. def on_copy_name(self):
  5468. self.defaults.report_usage("on_copy_name()")
  5469. obj = self.collection.get_active()
  5470. try:
  5471. name = obj.options["name"]
  5472. except AttributeError:
  5473. log.debug("on_copy_name() --> No object selected to copy it's name")
  5474. self.inform.emit('[WARNING_NOTCL]%s' %
  5475. _(" No object selected to copy it's name"))
  5476. return
  5477. self.clipboard.setText(name)
  5478. self.inform.emit(_("Name copied on clipboard ..."))
  5479. def on_mouse_click_over_plot(self, event):
  5480. """
  5481. Default actions are:
  5482. :param event: Contains information about the event, like which button
  5483. was clicked, the pixel coordinates and the axes coordinates.
  5484. :return: None
  5485. """
  5486. self.pos = []
  5487. if self.is_legacy is False:
  5488. event_pos = event.pos
  5489. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5490. # # Set the mouse button for panning
  5491. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5492. else:
  5493. event_pos = (event.xdata, event.ydata)
  5494. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5495. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5496. # So it can receive key presses
  5497. self.plotcanvas.native.setFocus()
  5498. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5499. if self.grid_status():
  5500. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5501. else:
  5502. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5503. try:
  5504. if event.button == 1:
  5505. # Reset here the relative coordinates so there is a new reference on the click position
  5506. if self.rel_point1 is None:
  5507. self.rel_point1 = self.pos
  5508. else:
  5509. self.rel_point2 = copy(self.rel_point1)
  5510. self.rel_point1 = self.pos
  5511. self.on_mouse_move_over_plot(event, origin_click=True)
  5512. except Exception as e:
  5513. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5514. def on_mouse_double_click_over_plot(self, event):
  5515. if event.button == 1:
  5516. self.doubleclick = True
  5517. def on_mouse_move_over_plot(self, event, origin_click=None):
  5518. """
  5519. Callback for the mouse motion event over the plot.
  5520. :param event: Contains information about the event.
  5521. :param origin_click
  5522. :return: None
  5523. """
  5524. if self.is_legacy is False:
  5525. event_pos = event.pos
  5526. if self.defaults["global_pan_button"] == '2':
  5527. pan_button = 2
  5528. else:
  5529. pan_button = 3
  5530. self.event_is_dragging = event.is_dragging
  5531. else:
  5532. event_pos = (event.xdata, event.ydata)
  5533. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5534. if self.defaults["global_pan_button"] == '2':
  5535. pan_button = 3
  5536. else:
  5537. pan_button = 2
  5538. self.event_is_dragging = self.plotcanvas.is_dragging
  5539. # So it can receive key presses but not when the Tcl Shell is active
  5540. if not self.ui.shell_dock.isVisible():
  5541. if not self.plotcanvas.native.hasFocus():
  5542. self.plotcanvas.native.setFocus()
  5543. self.pos_jump = event_pos
  5544. self.ui.popMenu.mouse_is_panning = False
  5545. if origin_click is None:
  5546. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5547. if event.button == pan_button and self.event_is_dragging == 1:
  5548. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5549. if self.ui.popMenu.popup_active:
  5550. self.ui.popMenu.popup_active = False
  5551. return
  5552. self.ui.popMenu.mouse_is_panning = True
  5553. return
  5554. if self.rel_point1 is not None:
  5555. try: # May fail in case mouse not within axes
  5556. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5557. if pos_canvas[0] is None or pos_canvas[1] is None:
  5558. return
  5559. if self.grid_status():
  5560. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5561. # Update cursor
  5562. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5563. symbol='++', edge_color=self.cursor_color_3D,
  5564. edge_width=self.defaults["global_cursor_width"],
  5565. size=self.defaults["global_cursor_size"])
  5566. else:
  5567. pos = (pos_canvas[0], pos_canvas[1])
  5568. self.dx = pos[0] - float(self.rel_point1[0])
  5569. self.dy = pos[1] - float(self.rel_point1[1])
  5570. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5571. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5572. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5573. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5574. units = self.defaults["units"].lower()
  5575. self.plotcanvas.text_hud.text = \
  5576. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5577. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5578. self.mouse = [pos[0], pos[1]]
  5579. # if the mouse is moved and the LMB is clicked then the action is a selection
  5580. if self.event_is_dragging == 1 and event.button == 1:
  5581. self.delete_selection_shape()
  5582. if self.dx < 0:
  5583. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5584. face_color=self.defaults['global_alt_sel_fill'])
  5585. self.selection_type = False
  5586. elif self.dx >= 0:
  5587. self.draw_moving_selection_shape(self.pos, pos)
  5588. self.selection_type = True
  5589. else:
  5590. self.selection_type = None
  5591. else:
  5592. self.selection_type = None
  5593. # hover effect - enabled in Preferences -> General -> GUI Settings
  5594. if self.defaults['global_hover']:
  5595. for obj in self.collection.get_list():
  5596. try:
  5597. # select the object(s) only if it is enabled (plotted)
  5598. if obj.options['plot']:
  5599. if obj not in self.collection.get_selected():
  5600. poly_obj = Polygon(
  5601. [(obj.options['xmin'], obj.options['ymin']),
  5602. (obj.options['xmax'], obj.options['ymin']),
  5603. (obj.options['xmax'], obj.options['ymax']),
  5604. (obj.options['xmin'], obj.options['ymax'])]
  5605. )
  5606. if Point(pos).within(poly_obj):
  5607. if obj.isHovering is False:
  5608. obj.isHovering = True
  5609. obj.notHovering = True
  5610. # create the selection box around the selected object
  5611. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5612. else:
  5613. if obj.notHovering is True:
  5614. obj.notHovering = False
  5615. obj.isHovering = False
  5616. self.delete_hover_shape()
  5617. except Exception:
  5618. # the Exception here will happen if we try to select on screen and we have an
  5619. # newly (and empty) just created Geometry or Excellon object that do not have the
  5620. # xmin, xmax, ymin, ymax options.
  5621. # In this case poly_obj creation (see above) will fail
  5622. pass
  5623. except Exception as e:
  5624. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5625. self.ui.position_label.setText("")
  5626. # self.ui.rel_position_label.setText("")
  5627. self.mouse = None
  5628. def on_mouse_click_release_over_plot(self, event):
  5629. """
  5630. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5631. and has been registered in ''self.__init__()''.
  5632. :param event: contains information about the event.
  5633. :return:
  5634. """
  5635. if self.is_legacy is False:
  5636. event_pos = event.pos
  5637. right_button = 2
  5638. else:
  5639. event_pos = (event.xdata, event.ydata)
  5640. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5641. right_button = 3
  5642. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5643. if self.grid_status():
  5644. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5645. else:
  5646. pos = (pos_canvas[0], pos_canvas[1])
  5647. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5648. # canvas menu
  5649. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5650. self.ui.popMenu.mouse_is_panning = False
  5651. self.cursor = QtGui.QCursor()
  5652. self.populate_cmenu_grids()
  5653. self.ui.popMenu.popup(self.cursor.pos())
  5654. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5655. # selection and then select a type of selection ("enclosing" or "touching")
  5656. if event.button == 1: # left click
  5657. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5658. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5659. if modifiers == QtCore.Qt.ShiftModifier:
  5660. # do not auto open the Project Tab
  5661. self.click_noproject = True
  5662. self.clipboard.setText(
  5663. self.defaults["global_point_clipboard_format"] %
  5664. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5665. )
  5666. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5667. return
  5668. if self.doubleclick is True:
  5669. self.doubleclick = False
  5670. if self.collection.get_selected():
  5671. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5672. if self.ui.splitter.sizes()[0] == 0:
  5673. self.ui.splitter.setSizes([1, 1])
  5674. try:
  5675. # delete the selection shape(S) as it may be in the way
  5676. self.delete_selection_shape()
  5677. self.delete_hover_shape()
  5678. except Exception as e:
  5679. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5680. return
  5681. else:
  5682. # WORKAROUND for LEGACY MODE
  5683. if self.is_legacy is True:
  5684. # if there is no move on canvas then we have no dragging selection
  5685. if self.dx == 0 or self.dy == 0:
  5686. self.selection_type = None
  5687. if self.selection_type is not None:
  5688. try:
  5689. self.selection_area_handler(self.pos, pos, self.selection_type)
  5690. self.selection_type = None
  5691. except Exception as e:
  5692. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5693. return
  5694. else:
  5695. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5696. if key_modifier == QtCore.Qt.ShiftModifier:
  5697. mod_key = 'Shift'
  5698. elif key_modifier == QtCore.Qt.ControlModifier:
  5699. mod_key = 'Control'
  5700. else:
  5701. mod_key = None
  5702. try:
  5703. if self.command_active is None:
  5704. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5705. # deselect, and if it's not selected then it will be selected
  5706. # If there is no active command (self.command_active is None) then we check if we clicked
  5707. # on a object by checking the bounding limits against mouse click position
  5708. if mod_key == self.defaults["global_mselect_key"]:
  5709. self.select_objects(key='multisel')
  5710. else:
  5711. # If there is no active command (self.command_active is None) then we check if
  5712. # we clicked on a object by checking the bounding limits against mouse click position
  5713. self.select_objects()
  5714. self.delete_hover_shape()
  5715. except Exception as e:
  5716. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5717. return
  5718. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5719. """
  5720. :param start_pos: mouse position when the selection LMB click was done
  5721. :param end_pos: mouse position when the left mouse button is released
  5722. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5723. :return:
  5724. """
  5725. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5726. # delete previous selection shape
  5727. self.delete_selection_shape()
  5728. # make all objects inactive
  5729. self.collection.set_all_inactive()
  5730. for obj in self.collection.get_list():
  5731. try:
  5732. # select the object(s) only if it is enabled (plotted)
  5733. if obj.options['plot']:
  5734. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5735. (obj.options['xmax'], obj.options['ymin']),
  5736. (obj.options['xmax'], obj.options['ymax']),
  5737. (obj.options['xmin'], obj.options['ymax'])])
  5738. if sel_type is True:
  5739. if poly_obj.within(poly_selection):
  5740. # create the selection box around the selected object
  5741. if self.defaults['global_selection_shape'] is True:
  5742. self.draw_selection_shape(obj)
  5743. self.collection.set_active(obj.options['name'])
  5744. else:
  5745. if poly_selection.intersects(poly_obj):
  5746. # create the selection box around the selected object
  5747. if self.defaults['global_selection_shape'] is True:
  5748. self.draw_selection_shape(obj)
  5749. self.collection.set_active(obj.options['name'])
  5750. obj.selection_shape_drawn = True
  5751. except Exception as e:
  5752. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5753. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5754. # In this case poly_obj creation (see above) will fail
  5755. log.debug("App.selection_area_handler() --> %s" % str(e))
  5756. def select_objects(self, key=None):
  5757. """
  5758. Will select objects clicked on canvas
  5759. :param key: for future use in cumulative selection
  5760. :return:
  5761. """
  5762. # list where we store the overlapped objects under our mouse left click position
  5763. if key is None:
  5764. self.objects_under_the_click_list = []
  5765. # Populate the list with the overlapped objects on the click position
  5766. curr_x, curr_y = self.pos
  5767. for obj in self.all_objects_list:
  5768. # ScriptObject and DocumentObject objects can't be selected
  5769. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5770. continue
  5771. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5772. continue
  5773. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5774. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5775. if obj.options['name'] not in self.objects_under_the_click_list:
  5776. if obj.options['plot']:
  5777. # add objects to the objects_under_the_click list only if the object is plotted
  5778. # (active and not disabled)
  5779. self.objects_under_the_click_list.append(obj.options['name'])
  5780. try:
  5781. if self.objects_under_the_click_list:
  5782. curr_sel_obj = self.collection.get_active()
  5783. # case when there is only an object under the click and we toggle it
  5784. if len(self.objects_under_the_click_list) == 1:
  5785. if curr_sel_obj is None:
  5786. self.collection.set_active(self.objects_under_the_click_list[0])
  5787. curr_sel_obj = self.collection.get_active()
  5788. # create the selection box around the selected object
  5789. if self.defaults['global_selection_shape'] is True:
  5790. self.draw_selection_shape(curr_sel_obj)
  5791. curr_sel_obj.selection_shape_drawn = True
  5792. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5793. self.on_objects_selection(False)
  5794. self.delete_selection_shape()
  5795. curr_sel_obj.selection_shape_drawn = False
  5796. self.collection.set_active(self.objects_under_the_click_list[0])
  5797. curr_sel_obj = self.collection.get_active()
  5798. # create the selection box around the selected object
  5799. if self.defaults['global_selection_shape'] is True:
  5800. self.draw_selection_shape(curr_sel_obj)
  5801. curr_sel_obj.selection_shape_drawn = True
  5802. self.selected_message(curr_sel_obj=curr_sel_obj)
  5803. elif curr_sel_obj.selection_shape_drawn is False:
  5804. if self.defaults['global_selection_shape'] is True:
  5805. self.draw_selection_shape(curr_sel_obj)
  5806. curr_sel_obj.selection_shape_drawn = True
  5807. else:
  5808. self.on_objects_selection(False)
  5809. self.delete_selection_shape()
  5810. if self.call_source != 'app':
  5811. self.call_source = 'app'
  5812. self.selected_message(curr_sel_obj=curr_sel_obj)
  5813. else:
  5814. # If there is no selected object
  5815. # make active the first element of the overlapped objects list
  5816. if self.collection.get_active() is None:
  5817. self.collection.set_active(self.objects_under_the_click_list[0])
  5818. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5819. name_sel_obj = self.collection.get_active().options['name']
  5820. # In case that there is a selected object but it is not in the overlapped object list
  5821. # make that object inactive and activate the first element in the overlapped object list
  5822. if name_sel_obj not in self.objects_under_the_click_list:
  5823. self.collection.set_inactive(name_sel_obj)
  5824. name_sel_obj = self.objects_under_the_click_list[0]
  5825. self.collection.set_active(name_sel_obj)
  5826. else:
  5827. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5828. self.collection.set_all_inactive()
  5829. self.collection.set_active(
  5830. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5831. curr_sel_obj = self.collection.get_active()
  5832. # delete the possible selection box around a possible selected object
  5833. self.delete_selection_shape()
  5834. curr_sel_obj.selection_shape_drawn = False
  5835. # create the selection box around the selected object
  5836. if self.defaults['global_selection_shape'] is True:
  5837. self.draw_selection_shape(curr_sel_obj)
  5838. curr_sel_obj.selection_shape_drawn = True
  5839. self.selected_message(curr_sel_obj=curr_sel_obj)
  5840. else:
  5841. # deselect everything
  5842. self.on_objects_selection(False)
  5843. # delete the possible selection box around a possible selected object
  5844. self.delete_selection_shape()
  5845. for o in self.collection.get_list():
  5846. o.selection_shape_drawn = False
  5847. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5848. # only when working on App
  5849. if self.call_source == 'app':
  5850. if self.click_noproject is False:
  5851. # if the Tool Tab is in focus don't change focus to Project Tab
  5852. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5853. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5854. else:
  5855. # restore auto open the Project Tab
  5856. self.click_noproject = False
  5857. # delete any text in the status bar, implicitly the last object name that was selected
  5858. # self.inform.emit("")
  5859. else:
  5860. self.call_source = 'app'
  5861. except Exception as e:
  5862. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5863. def selected_message(self, curr_sel_obj):
  5864. if curr_sel_obj:
  5865. if curr_sel_obj.kind == 'gerber':
  5866. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5867. color='green',
  5868. name=str(curr_sel_obj.options['name']),
  5869. tx=_("selected"))
  5870. )
  5871. elif curr_sel_obj.kind == 'excellon':
  5872. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5873. color='brown',
  5874. name=str(curr_sel_obj.options['name']),
  5875. tx=_("selected"))
  5876. )
  5877. elif curr_sel_obj.kind == 'cncjob':
  5878. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5879. color='blue',
  5880. name=str(curr_sel_obj.options['name']),
  5881. tx=_("selected"))
  5882. )
  5883. elif curr_sel_obj.kind == 'geometry':
  5884. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5885. color='red',
  5886. name=str(curr_sel_obj.options['name']),
  5887. tx=_("selected"))
  5888. )
  5889. def delete_hover_shape(self):
  5890. self.hover_shapes.clear()
  5891. self.hover_shapes.redraw()
  5892. def draw_hover_shape(self, sel_obj, color=None):
  5893. """
  5894. :param sel_obj: The object for which the hover shape must be drawn
  5895. :param color: The color of the hover shape
  5896. :return: None
  5897. """
  5898. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5899. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5900. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5901. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5902. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5903. if self.defaults['units'].upper() == 'MM':
  5904. hover_rect = hover_rect.buffer(-0.1)
  5905. hover_rect = hover_rect.buffer(0.2)
  5906. else:
  5907. hover_rect = hover_rect.buffer(-0.00393)
  5908. hover_rect = hover_rect.buffer(0.00787)
  5909. # if color:
  5910. # face = Color(color)
  5911. # face.alpha = 0.2
  5912. # outline = Color(color, alpha=0.8)
  5913. # else:
  5914. # face = Color(self.defaults['global_sel_fill'])
  5915. # face.alpha = 0.2
  5916. # outline = self.defaults['global_sel_line']
  5917. if color:
  5918. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5919. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5920. else:
  5921. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5922. outline = self.defaults['global_sel_line']
  5923. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5924. if self.is_legacy is True:
  5925. self.hover_shapes.redraw()
  5926. def delete_selection_shape(self):
  5927. self.move_tool.sel_shapes.clear()
  5928. self.move_tool.sel_shapes.redraw()
  5929. def draw_selection_shape(self, sel_obj, color=None):
  5930. """
  5931. Will draw a selection shape around the selected object.
  5932. :param sel_obj: The object for which the selection shape must be drawn
  5933. :param color: The color for the selection shape.
  5934. :return: None
  5935. """
  5936. if sel_obj is None:
  5937. return
  5938. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5939. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5940. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5941. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5942. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5943. if self.defaults['units'].upper() == 'MM':
  5944. sel_rect = sel_rect.buffer(-0.1)
  5945. sel_rect = sel_rect.buffer(0.2)
  5946. else:
  5947. sel_rect = sel_rect.buffer(-0.00393)
  5948. sel_rect = sel_rect.buffer(0.00787)
  5949. if color:
  5950. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5951. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5952. else:
  5953. if self.is_legacy is False:
  5954. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5955. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5956. else:
  5957. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5958. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5959. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5960. color=outline,
  5961. face_color=face,
  5962. update=True,
  5963. layer=0,
  5964. tolerance=None))
  5965. if self.is_legacy is True:
  5966. self.move_tool.sel_shapes.redraw()
  5967. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5968. """
  5969. Will draw a selection shape when dragging mouse on canvas.
  5970. :param old_coords: Old coordinates
  5971. :param coords: New coordinates
  5972. :param kwargs: Keyword arguments
  5973. :return:
  5974. """
  5975. if 'color' in kwargs:
  5976. color = kwargs['color']
  5977. else:
  5978. color = self.defaults['global_sel_line']
  5979. if 'face_color' in kwargs:
  5980. face_color = kwargs['face_color']
  5981. else:
  5982. face_color = self.defaults['global_sel_fill']
  5983. if 'face_alpha' in kwargs:
  5984. face_alpha = kwargs['face_alpha']
  5985. else:
  5986. face_alpha = 0.3
  5987. x0, y0 = old_coords
  5988. x1, y1 = coords
  5989. pt1 = (x0, y0)
  5990. pt2 = (x1, y0)
  5991. pt3 = (x1, y1)
  5992. pt4 = (x0, y1)
  5993. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5994. # color_t = Color(face_color)
  5995. # color_t.alpha = face_alpha
  5996. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5997. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5998. layer=0, tolerance=None)
  5999. if self.is_legacy is True:
  6000. self.move_tool.sel_shapes.redraw()
  6001. def on_file_new_click(self):
  6002. """
  6003. Callback for menu item File -> New.
  6004. Executed on clicking the Menu -> File -> New Project
  6005. :return:
  6006. """
  6007. if self.collection.get_list() and self.should_we_save:
  6008. msgbox = QtWidgets.QMessageBox()
  6009. # msgbox.setText("<B>Save changes ...</B>")
  6010. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6011. "Creating a New project will delete them.\n"
  6012. "Do you want to Save the project?"))
  6013. msgbox.setWindowTitle(_("Save changes"))
  6014. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6015. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6016. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6017. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6018. msgbox.setDefaultButton(bt_yes)
  6019. msgbox.exec_()
  6020. response = msgbox.clickedButton()
  6021. if response == bt_yes:
  6022. self.on_file_saveprojectas()
  6023. elif response == bt_cancel:
  6024. return
  6025. elif response == bt_no:
  6026. self.on_file_new()
  6027. else:
  6028. self.on_file_new()
  6029. self.inform.emit('[success] %s...' % _("New Project created"))
  6030. def on_file_new(self, cli=None):
  6031. """
  6032. Returns the application to its startup state. This method is thread-safe.
  6033. :param cli: Boolean. If True this method was run from command line
  6034. :return: None
  6035. """
  6036. self.defaults.report_usage("on_file_new")
  6037. # Remove everything from memory
  6038. App.log.debug("on_file_new()")
  6039. # close any editor that might be open
  6040. if self.call_source != 'app':
  6041. self.editor2object(cleanup=True)
  6042. # ## EDITOR section
  6043. self.geo_editor = FlatCAMGeoEditor(self)
  6044. self.exc_editor = FlatCAMExcEditor(self)
  6045. self.grb_editor = FlatCAMGrbEditor(self)
  6046. # Clear pool
  6047. self.clear_pool()
  6048. for obj in self.collection.get_list():
  6049. # delete shapes left drawn from mark shape_collections, if any
  6050. if isinstance(obj, GerberObject):
  6051. try:
  6052. for el in obj.mark_shapes:
  6053. obj.mark_shapes[el].clear(update=True)
  6054. obj.mark_shapes[el].enabled = False
  6055. del el
  6056. except AttributeError:
  6057. pass
  6058. # also delete annotation shapes, if any
  6059. elif isinstance(obj, CNCJobObject):
  6060. try:
  6061. obj.text_col.enabled = False
  6062. del obj.text_col
  6063. obj.annotation.clear(update=True)
  6064. del obj.annotation
  6065. except AttributeError:
  6066. pass
  6067. # delete the exclusion areas
  6068. self.exc_areas.clear_shapes()
  6069. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6070. self.shell.init_tcl()
  6071. # delete any selection shape on canvas
  6072. self.delete_selection_shape()
  6073. # delete all FlatCAM objects
  6074. self.collection.delete_all()
  6075. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  6076. self.setup_component_editor()
  6077. # Clear project filename
  6078. self.project_filename = None
  6079. # Load the application defaults
  6080. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6081. # Re-fresh project options
  6082. self.on_options_app2project()
  6083. # Init FlatCAMTools
  6084. self.init_tools()
  6085. # Try to close all tabs in the PlotArea but only if the GUI is active (CLI is None)
  6086. if cli is None:
  6087. # we need to go in reverse because once we remove a tab then the index changes
  6088. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  6089. # and so on. Therefore the deletion should be done in reverse
  6090. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  6091. for index in range(wdg_count, -1, -1):
  6092. try:
  6093. self.ui.plot_tab_area.closeTab(index)
  6094. except Exception as e:
  6095. log.debug("App.on_file_new() --> %s" % str(e))
  6096. # # And then add again the Plot Area
  6097. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  6098. self.ui.plot_tab_area.protectTab(0)
  6099. # take the focus of the Notebook on Project Tab.
  6100. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6101. self.set_ui_title(name=_("New Project - Not saved"))
  6102. def obj_properties(self):
  6103. """
  6104. Will launch the object Properties Tool
  6105. :return:
  6106. """
  6107. self.defaults.report_usage("obj_properties()")
  6108. self.properties_tool.run(toggle=False)
  6109. def on_project_context_save(self):
  6110. """
  6111. Wrapper, will save the object function of it's type
  6112. :return:
  6113. """
  6114. obj = self.collection.get_active()
  6115. if type(obj) == GeometryObject:
  6116. self.on_file_exportdxf()
  6117. elif type(obj) == ExcellonObject:
  6118. self.on_file_saveexcellon()
  6119. elif type(obj) == CNCJobObject:
  6120. obj.on_exportgcode_button_click()
  6121. elif type(obj) == GerberObject:
  6122. self.on_file_savegerber()
  6123. elif type(obj) == ScriptObject:
  6124. self.on_file_savescript()
  6125. elif type(obj) == DocumentObject:
  6126. self.on_file_savedocument()
  6127. def obj_move(self):
  6128. """
  6129. Callback for the Move menu entry in various Context Menu's.
  6130. :return:
  6131. """
  6132. self.defaults.report_usage("obj_move()")
  6133. self.move_tool.run(toggle=False)
  6134. def on_fileopengerber(self, signal, name=None):
  6135. """
  6136. File menu callback for opening a Gerber.
  6137. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6138. :param name:
  6139. :return: None
  6140. """
  6141. self.defaults.report_usage("on_fileopengerber")
  6142. App.log.debug("on_fileopengerber()")
  6143. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6144. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6145. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6146. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6147. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6148. "*.mil);;" \
  6149. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6150. "Allegro Files (*.art);;" \
  6151. "Mentor Files (*.pho *.gdo);;" \
  6152. "All Files (*.*)"
  6153. if name is None:
  6154. try:
  6155. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6156. directory=self.get_last_folder(),
  6157. filter=_filter_)
  6158. except TypeError:
  6159. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6160. filenames = [str(filename) for filename in filenames]
  6161. else:
  6162. filenames = [name]
  6163. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6164. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6165. _("Opening Gerber file.")),
  6166. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6167. color=QtGui.QColor("gray"))
  6168. if len(filenames) == 0:
  6169. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6170. else:
  6171. for filename in filenames:
  6172. if filename != '':
  6173. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6174. def on_fileopenexcellon(self, signal, name=None):
  6175. """
  6176. File menu callback for opening an Excellon file.
  6177. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6178. :param name:
  6179. :return: None
  6180. """
  6181. self.defaults.report_usage("on_fileopenexcellon")
  6182. App.log.debug("on_fileopenexcellon()")
  6183. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6184. "All Files (*.*)"
  6185. if name is None:
  6186. try:
  6187. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6188. directory=self.get_last_folder(),
  6189. filter=_filter_)
  6190. except TypeError:
  6191. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6192. filenames = [str(filename) for filename in filenames]
  6193. else:
  6194. filenames = [str(name)]
  6195. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6196. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6197. _("Opening Excellon file.")),
  6198. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6199. color=QtGui.QColor("gray"))
  6200. if len(filenames) == 0:
  6201. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6202. else:
  6203. for filename in filenames:
  6204. if filename != '':
  6205. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6206. def on_fileopengcode(self, signal, name=None):
  6207. """
  6208. File menu call back for opening gcode.
  6209. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6210. :param name:
  6211. :return:
  6212. """
  6213. self.defaults.report_usage("on_fileopengcode")
  6214. App.log.debug("on_fileopengcode()")
  6215. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6216. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6217. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6218. "All Files (*.*)"
  6219. if name is None:
  6220. try:
  6221. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6222. directory=self.get_last_folder(),
  6223. filter=_filter_)
  6224. except TypeError:
  6225. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6226. filenames = [str(filename) for filename in filenames]
  6227. else:
  6228. filenames = [name]
  6229. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6230. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6231. _("Opening G-Code file.")),
  6232. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6233. color=QtGui.QColor("gray"))
  6234. if len(filenames) == 0:
  6235. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6236. else:
  6237. for filename in filenames:
  6238. if filename != '':
  6239. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6240. def on_file_openproject(self, signal):
  6241. """
  6242. File menu callback for opening a project.
  6243. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6244. :return: None
  6245. """
  6246. self.defaults.report_usage("on_file_openproject")
  6247. App.log.debug("on_file_openproject()")
  6248. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6249. try:
  6250. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6251. directory=self.get_last_folder(), filter=_filter_)
  6252. except TypeError:
  6253. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6254. # The Qt methods above will return a QString which can cause problems later.
  6255. # So far json.dump() will fail to serialize it.
  6256. # TODO: Improve the serialization methods and remove this fix.
  6257. filename = str(filename)
  6258. if filename == "":
  6259. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6260. else:
  6261. # self.worker_task.emit({'fcn': self.open_project,
  6262. # 'params': [filename]})
  6263. # The above was failing because open_project() is not
  6264. # thread safe. The new_project()
  6265. self.open_project(filename)
  6266. def on_fileopenhpgl2(self, signal, name=None):
  6267. """
  6268. File menu callback for opening a HPGL2.
  6269. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6270. :param name:
  6271. :return: None
  6272. """
  6273. self.defaults.report_usage("on_fileopenhpgl2")
  6274. App.log.debug("on_fileopenhpgl2()")
  6275. _filter_ = "HPGL2 Files (*.plt);;" \
  6276. "All Files (*.*)"
  6277. if name is None:
  6278. try:
  6279. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6280. directory=self.get_last_folder(),
  6281. filter=_filter_)
  6282. except TypeError:
  6283. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6284. filenames = [str(filename) for filename in filenames]
  6285. else:
  6286. filenames = [name]
  6287. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6288. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6289. _("Opening HPGL2 file.")),
  6290. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6291. color=QtGui.QColor("gray"))
  6292. if len(filenames) == 0:
  6293. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6294. else:
  6295. for filename in filenames:
  6296. if filename != '':
  6297. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6298. def on_file_openconfig(self, signal):
  6299. """
  6300. File menu callback for opening a config file.
  6301. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6302. :return: None
  6303. """
  6304. self.defaults.report_usage("on_file_openconfig")
  6305. App.log.debug("on_file_openconfig()")
  6306. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6307. try:
  6308. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6309. directory=self.data_path, filter=_filter_)
  6310. except TypeError:
  6311. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6312. filter=_filter_)
  6313. if filename == "":
  6314. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6315. else:
  6316. self.open_config_file(filename)
  6317. def on_file_exportsvg(self):
  6318. """
  6319. Callback for menu item File->Export SVG.
  6320. :return: None
  6321. """
  6322. self.defaults.report_usage("on_file_exportsvg")
  6323. App.log.debug("on_file_exportsvg()")
  6324. obj = self.collection.get_active()
  6325. if obj is None:
  6326. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6327. msg = _("Please Select a Geometry object to export")
  6328. msgbox = QtWidgets.QMessageBox()
  6329. msgbox.setInformativeText(msg)
  6330. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6331. msgbox.setDefaultButton(bt_ok)
  6332. msgbox.exec_()
  6333. return
  6334. # Check for more compatible types and add as required
  6335. if (not isinstance(obj, GeometryObject)
  6336. and not isinstance(obj, GerberObject)
  6337. and not isinstance(obj, CNCJobObject)
  6338. and not isinstance(obj, ExcellonObject)):
  6339. msg = '[ERROR_NOTCL] %s' % \
  6340. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6341. msgbox = QtWidgets.QMessageBox()
  6342. msgbox.setInformativeText(msg)
  6343. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6344. msgbox.setDefaultButton(bt_ok)
  6345. msgbox.exec_()
  6346. return
  6347. name = obj.options["name"]
  6348. _filter = "SVG File (*.svg);;All Files (*.*)"
  6349. try:
  6350. filename, _f = FCFileSaveDialog.get_saved_filename(
  6351. caption=_("Export SVG"),
  6352. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6353. filter=_filter)
  6354. except TypeError:
  6355. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6356. filename = str(filename)
  6357. if filename == "":
  6358. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6359. return
  6360. else:
  6361. self.export_svg(name, filename)
  6362. if self.defaults["global_open_style"] is False:
  6363. self.file_opened.emit("SVG", filename)
  6364. self.file_saved.emit("SVG", filename)
  6365. def on_file_exportpng(self):
  6366. self.defaults.report_usage("on_file_exportpng")
  6367. App.log.debug("on_file_exportpng()")
  6368. self.date = str(datetime.today()).rpartition('.')[0]
  6369. self.date = ''.join(c for c in self.date if c not in ':-')
  6370. self.date = self.date.replace(' ', '_')
  6371. if self.is_legacy is False:
  6372. image = _screenshot()
  6373. data = np.asarray(image)
  6374. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6375. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6376. return
  6377. filter_ = "PNG File (*.png);;All Files (*.*)"
  6378. try:
  6379. filename, _f = FCFileSaveDialog.get_saved_filename(
  6380. caption=_("Export PNG Image"),
  6381. directory=self.get_last_save_folder() + '/png_' + self.date,
  6382. filter=filter_)
  6383. except TypeError:
  6384. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6385. filename = str(filename)
  6386. if filename == "":
  6387. self.inform.emit(_("Cancelled."))
  6388. return
  6389. else:
  6390. if self.is_legacy is False:
  6391. write_png(filename, data)
  6392. else:
  6393. self.plotcanvas.figure.savefig(filename)
  6394. if self.defaults["global_open_style"] is False:
  6395. self.file_opened.emit("png", filename)
  6396. self.file_saved.emit("png", filename)
  6397. def on_file_savegerber(self):
  6398. """
  6399. Callback for menu item in Project context menu.
  6400. :return: None
  6401. """
  6402. self.defaults.report_usage("on_file_savegerber")
  6403. App.log.debug("on_file_savegerber()")
  6404. obj = self.collection.get_active()
  6405. if obj is None:
  6406. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6407. return
  6408. # Check for more compatible types and add as required
  6409. if not isinstance(obj, GerberObject):
  6410. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6411. return
  6412. name = self.collection.get_active().options["name"]
  6413. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6414. try:
  6415. filename, _f = FCFileSaveDialog.get_saved_filename(
  6416. caption="Save Gerber source file",
  6417. directory=self.get_last_save_folder() + '/' + name,
  6418. filter=_filter)
  6419. except TypeError:
  6420. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6421. filename = str(filename)
  6422. if filename == "":
  6423. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6424. return
  6425. else:
  6426. self.save_source_file(name, filename)
  6427. if self.defaults["global_open_style"] is False:
  6428. self.file_opened.emit("Gerber", filename)
  6429. self.file_saved.emit("Gerber", filename)
  6430. def on_file_savescript(self):
  6431. """
  6432. Callback for menu item in Project context menu.
  6433. :return: None
  6434. """
  6435. self.defaults.report_usage("on_file_savescript")
  6436. App.log.debug("on_file_savescript()")
  6437. obj = self.collection.get_active()
  6438. if obj is None:
  6439. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6440. return
  6441. # Check for more compatible types and add as required
  6442. if not isinstance(obj, ScriptObject):
  6443. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6444. return
  6445. name = self.collection.get_active().options["name"]
  6446. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6447. try:
  6448. filename, _f = FCFileSaveDialog.get_saved_filename(
  6449. caption="Save Script source file",
  6450. directory=self.get_last_save_folder() + '/' + name,
  6451. filter=_filter)
  6452. except TypeError:
  6453. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6454. filename = str(filename)
  6455. if filename == "":
  6456. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6457. return
  6458. else:
  6459. self.save_source_file(name, filename)
  6460. if self.defaults["global_open_style"] is False:
  6461. self.file_opened.emit("Script", filename)
  6462. self.file_saved.emit("Script", filename)
  6463. def on_file_savedocument(self):
  6464. """
  6465. Callback for menu item in Project context menu.
  6466. :return: None
  6467. """
  6468. self.defaults.report_usage("on_file_savedocument")
  6469. App.log.debug("on_file_savedocument()")
  6470. obj = self.collection.get_active()
  6471. if obj is None:
  6472. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6473. return
  6474. # Check for more compatible types and add as required
  6475. if not isinstance(obj, ScriptObject):
  6476. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6477. return
  6478. name = self.collection.get_active().options["name"]
  6479. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6480. try:
  6481. filename, _f = FCFileSaveDialog.get_saved_filename(
  6482. caption="Save Document source file",
  6483. directory=self.get_last_save_folder() + '/' + name,
  6484. filter=_filter)
  6485. except TypeError:
  6486. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6487. filename = str(filename)
  6488. if filename == "":
  6489. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6490. return
  6491. else:
  6492. self.save_source_file(name, filename)
  6493. if self.defaults["global_open_style"] is False:
  6494. self.file_opened.emit("Document", filename)
  6495. self.file_saved.emit("Document", filename)
  6496. def on_file_saveexcellon(self):
  6497. """
  6498. Callback for menu item in project context menu.
  6499. :return: None
  6500. """
  6501. self.defaults.report_usage("on_file_saveexcellon")
  6502. App.log.debug("on_file_saveexcellon()")
  6503. obj = self.collection.get_active()
  6504. if obj is None:
  6505. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6506. return
  6507. # Check for more compatible types and add as required
  6508. if not isinstance(obj, ExcellonObject):
  6509. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6510. return
  6511. name = self.collection.get_active().options["name"]
  6512. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6513. try:
  6514. filename, _f = FCFileSaveDialog.get_saved_filename(
  6515. caption=_("Save Excellon source file"),
  6516. directory=self.get_last_save_folder() + '/' + name,
  6517. filter=_filter)
  6518. except TypeError:
  6519. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6520. filename = str(filename)
  6521. if filename == "":
  6522. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6523. return
  6524. else:
  6525. self.save_source_file(name, filename)
  6526. if self.defaults["global_open_style"] is False:
  6527. self.file_opened.emit("Excellon", filename)
  6528. self.file_saved.emit("Excellon", filename)
  6529. def on_file_exportexcellon(self):
  6530. """
  6531. Callback for menu item File->Export->Excellon.
  6532. :return: None
  6533. """
  6534. self.defaults.report_usage("on_file_exportexcellon")
  6535. App.log.debug("on_file_exportexcellon()")
  6536. obj = self.collection.get_active()
  6537. if obj is None:
  6538. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6539. return
  6540. # Check for more compatible types and add as required
  6541. if not isinstance(obj, ExcellonObject):
  6542. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6543. return
  6544. name = self.collection.get_active().options["name"]
  6545. _filter = self.defaults["excellon_save_filters"]
  6546. try:
  6547. filename, _f = FCFileSaveDialog.get_saved_filename(
  6548. caption=_("Export Excellon"),
  6549. directory=self.get_last_save_folder() + '/' + name,
  6550. filter=_filter)
  6551. except TypeError:
  6552. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6553. filename = str(filename)
  6554. if filename == "":
  6555. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6556. return
  6557. else:
  6558. used_extension = filename.rpartition('.')[2]
  6559. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6560. self.export_excellon(name, filename)
  6561. if self.defaults["global_open_style"] is False:
  6562. self.file_opened.emit("Excellon", filename)
  6563. self.file_saved.emit("Excellon", filename)
  6564. def on_file_exportgerber(self):
  6565. """
  6566. Callback for menu item File->Export->Gerber.
  6567. :return: None
  6568. """
  6569. self.defaults.report_usage("on_file_exportgerber")
  6570. App.log.debug("on_file_exportgerber()")
  6571. obj = self.collection.get_active()
  6572. if obj is None:
  6573. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6574. return
  6575. # Check for more compatible types and add as required
  6576. if not isinstance(obj, GerberObject):
  6577. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6578. return
  6579. name = self.collection.get_active().options["name"]
  6580. _filter_ = self.defaults['gerber_save_filters']
  6581. try:
  6582. filename, _f = FCFileSaveDialog.get_saved_filename(
  6583. caption=_("Export Gerber"),
  6584. directory=self.get_last_save_folder() + '/' + name,
  6585. filter=_filter_)
  6586. except TypeError:
  6587. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6588. filename = str(filename)
  6589. if filename == "":
  6590. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6591. return
  6592. else:
  6593. used_extension = filename.rpartition('.')[2]
  6594. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6595. self.export_gerber(name, filename)
  6596. if self.defaults["global_open_style"] is False:
  6597. self.file_opened.emit("Gerber", filename)
  6598. self.file_saved.emit("Gerber", filename)
  6599. def on_file_exportdxf(self):
  6600. """
  6601. Callback for menu item File->Export DXF.
  6602. :return: None
  6603. """
  6604. self.defaults.report_usage("on_file_exportdxf")
  6605. App.log.debug("on_file_exportdxf()")
  6606. obj = self.collection.get_active()
  6607. if obj is None:
  6608. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6609. msg = _("Please Select a Geometry object to export")
  6610. msgbox = QtWidgets.QMessageBox()
  6611. msgbox.setInformativeText(msg)
  6612. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6613. msgbox.setDefaultButton(bt_ok)
  6614. msgbox.exec_()
  6615. return
  6616. # Check for more compatible types and add as required
  6617. if not isinstance(obj, GeometryObject):
  6618. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6619. msgbox = QtWidgets.QMessageBox()
  6620. msgbox.setInformativeText(msg)
  6621. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6622. msgbox.setDefaultButton(bt_ok)
  6623. msgbox.exec_()
  6624. return
  6625. name = self.collection.get_active().options["name"]
  6626. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6627. try:
  6628. filename, _f = FCFileSaveDialog.get_saved_filename(
  6629. caption=_("Export DXF"),
  6630. directory=self.get_last_save_folder() + '/' + name,
  6631. filter=_filter_)
  6632. except TypeError:
  6633. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6634. filename = str(filename)
  6635. if filename == "":
  6636. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6637. return
  6638. else:
  6639. self.export_dxf(name, filename)
  6640. if self.defaults["global_open_style"] is False:
  6641. self.file_opened.emit("DXF", filename)
  6642. self.file_saved.emit("DXF", filename)
  6643. def on_file_importsvg(self, type_of_obj):
  6644. """
  6645. Callback for menu item File->Import SVG.
  6646. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6647. :type type_of_obj: str
  6648. :return: None
  6649. """
  6650. self.defaults.report_usage("on_file_importsvg")
  6651. App.log.debug("on_file_importsvg()")
  6652. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6653. try:
  6654. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6655. directory=self.get_last_folder(), filter=_filter_)
  6656. except TypeError:
  6657. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6658. filter=_filter_)
  6659. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6660. type_of_obj = "geometry"
  6661. filenames = [str(filename) for filename in filenames]
  6662. if len(filenames) == 0:
  6663. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6664. else:
  6665. for filename in filenames:
  6666. if filename != '':
  6667. self.worker_task.emit({'fcn': self.import_svg,
  6668. 'params': [filename, type_of_obj]})
  6669. def on_file_importdxf(self, type_of_obj):
  6670. """
  6671. Callback for menu item File->Import DXF.
  6672. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6673. :type type_of_obj: str
  6674. :return: None
  6675. """
  6676. self.defaults.report_usage("on_file_importdxf")
  6677. App.log.debug("on_file_importdxf()")
  6678. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6679. try:
  6680. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6681. directory=self.get_last_folder(),
  6682. filter=_filter_)
  6683. except TypeError:
  6684. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6685. filter=_filter_)
  6686. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6687. type_of_obj = "geometry"
  6688. filenames = [str(filename) for filename in filenames]
  6689. if len(filenames) == 0:
  6690. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6691. else:
  6692. for filename in filenames:
  6693. if filename != '':
  6694. self.worker_task.emit({'fcn': self.import_dxf,
  6695. 'params': [filename, type_of_obj]})
  6696. # ###############################################################################################################
  6697. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6698. # ###############################################################################################################
  6699. def init_code_editor(self, name):
  6700. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6701. # add the tab if it was closed
  6702. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6703. self.text_editor_tab.setObjectName('text_editor_tab')
  6704. # delete the absolute and relative position and messages in the infobar
  6705. self.ui.position_label.setText("")
  6706. # self.ui.rel_position_label.setText("")
  6707. # first clear previous text in text editor (if any)
  6708. self.text_editor_tab.code_editor.clear()
  6709. self.text_editor_tab.code_editor.setReadOnly(False)
  6710. self.toggle_codeeditor = True
  6711. self.text_editor_tab.code_editor.completer_enable = False
  6712. self.text_editor_tab.buttonRun.hide()
  6713. # make sure to keep a reference to the code editor
  6714. self.reference_code_editor = self.text_editor_tab.code_editor
  6715. # Switch plot_area to CNCJob tab
  6716. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6717. def on_view_source(self):
  6718. """
  6719. Called when the user wants to see the source file of the selected object
  6720. :return:
  6721. """
  6722. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6723. self.proc_container.view.set_busy(_("Loading..."))
  6724. try:
  6725. obj = self.collection.get_active()
  6726. except Exception as e:
  6727. log.debug("App.on_view_source() --> %s" % str(e))
  6728. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6729. return 'fail'
  6730. if obj is None:
  6731. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6732. return 'fail'
  6733. flt = "All Files (*.*)"
  6734. if obj.kind == 'gerber':
  6735. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6736. elif obj.kind == 'excellon':
  6737. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6738. elif obj.kind == 'cncjob':
  6739. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6740. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6741. # add the tab if it was closed
  6742. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6743. self.source_editor_tab.setObjectName('source_editor_tab')
  6744. # delete the absolute and relative position and messages in the infobar
  6745. self.ui.position_label.setText("")
  6746. # self.ui.rel_position_label.setText("")
  6747. # first clear previous text in text editor (if any)
  6748. self.source_editor_tab.code_editor.clear()
  6749. self.source_editor_tab.code_editor.setReadOnly(False)
  6750. self.source_editor_tab.code_editor.completer_enable = False
  6751. self.source_editor_tab.buttonRun.hide()
  6752. # Switch plot_area to CNCJob tab
  6753. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6754. try:
  6755. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6756. except TypeError:
  6757. pass
  6758. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6759. try:
  6760. self.source_editor_tab.buttonSave.clicked.disconnect()
  6761. except TypeError:
  6762. pass
  6763. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6764. # then append the text from GCode to the text editor
  6765. if obj.kind == 'cncjob':
  6766. try:
  6767. file = obj.export_gcode(
  6768. preamble=self.defaults["cncjob_prepend"],
  6769. postamble=self.defaults["cncjob_append"],
  6770. to_file=True)
  6771. if file == 'fail':
  6772. return 'fail'
  6773. except AttributeError:
  6774. self.inform.emit('[WARNING_NOTCL] %s' %
  6775. _("There is no selected object for which to see it's source file code."))
  6776. return 'fail'
  6777. else:
  6778. try:
  6779. file = StringIO(obj.source_file)
  6780. except (AttributeError, TypeError):
  6781. self.inform.emit('[WARNING_NOTCL] %s' %
  6782. _("There is no selected object for which to see it's source file code."))
  6783. return 'fail'
  6784. self.source_editor_tab.t_frame.hide()
  6785. try:
  6786. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6787. # for line in file:
  6788. # QtWidgets.QApplication.processEvents()
  6789. # proc_line = str(line).strip('\n')
  6790. # self.source_editor_tab.code_editor.append(proc_line)
  6791. except Exception as e:
  6792. log.debug('App.on_view_source() -->%s' % str(e))
  6793. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6794. return
  6795. self.source_editor_tab.handleTextChanged()
  6796. self.source_editor_tab.t_frame.show()
  6797. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6798. self.proc_container.view.set_idle()
  6799. # self.ui.show()
  6800. def on_toggle_code_editor(self):
  6801. self.defaults.report_usage("on_toggle_code_editor()")
  6802. if self.toggle_codeeditor is False:
  6803. self.init_code_editor(name=_("Code Editor"))
  6804. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6805. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6806. self.text_editor_tab.buttonSave.clicked.disconnect()
  6807. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6808. else:
  6809. for idx in range(self.ui.plot_tab_area.count()):
  6810. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6811. self.ui.plot_tab_area.closeTab(idx)
  6812. break
  6813. self.toggle_codeeditor = False
  6814. def on_code_editor_close(self):
  6815. self.toggle_codeeditor = False
  6816. def goto_text_line(self):
  6817. """
  6818. Will scroll a text to the specified text line.
  6819. :return: None
  6820. """
  6821. dia_box = Dialog_box(title=_("Go to Line ..."),
  6822. label=_("Line:"),
  6823. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6824. initial_text='')
  6825. try:
  6826. line = int(dia_box.location) - 1
  6827. except (ValueError, TypeError):
  6828. line = 0
  6829. if dia_box.ok:
  6830. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6831. # at the top of the window
  6832. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6833. # get the document() of the TextEditor
  6834. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6835. # create a Text Cursor based on the searched line
  6836. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6837. # set cursor of the code editor with the cursor at the searcehd line
  6838. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6839. def on_filenewscript(self, silent=False):
  6840. """
  6841. Will create a new script file and open it in the Code Editor
  6842. :param silent: if True will not display status messages
  6843. :param name: if specified will be the name of the new script
  6844. :param text: pass a source file to the newly created script to be loaded in it
  6845. :return: None
  6846. """
  6847. if silent is False:
  6848. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6849. # delete the absolute and relative position and messages in the infobar
  6850. self.ui.position_label.setText("")
  6851. # self.ui.rel_position_label.setText("")
  6852. self.new_script_object()
  6853. # script_text = script_obj.source_file
  6854. #
  6855. # self.proc_container.view.set_busy(_("Loading..."))
  6856. # script_obj.script_editor_tab.t_frame.hide()
  6857. #
  6858. # script_obj.script_editor_tab.t_frame.show()
  6859. # self.proc_container.view.set_idle()
  6860. def on_fileopenscript(self, name=None, silent=False):
  6861. """
  6862. Will open a Tcl script file into the Code Editor
  6863. :param silent: if True will not display status messages
  6864. :param name: name of a Tcl script file to open
  6865. :return: None
  6866. """
  6867. self.defaults.report_usage("on_fileopenscript")
  6868. App.log.debug("on_fileopenscript()")
  6869. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6870. "All Files (*.*)"
  6871. if name:
  6872. filenames = [name]
  6873. else:
  6874. try:
  6875. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6876. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6877. except TypeError:
  6878. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6879. if len(filenames) == 0:
  6880. if silent is False:
  6881. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6882. else:
  6883. for filename in filenames:
  6884. if filename != '':
  6885. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6886. def on_fileopenscript_example(self, name=None, silent=False):
  6887. """
  6888. Will open a Tcl script file into the Code Editor
  6889. :param silent: if True will not display status messages
  6890. :param name: name of a Tcl script file to open
  6891. :return:
  6892. """
  6893. self.defaults.report_usage("on_fileopenscript_example")
  6894. log.debug("on_fileopenscript_example()")
  6895. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6896. "All Files (*.*)"
  6897. # test if the app was frozen and choose the path for the configuration file
  6898. if getattr(sys, "frozen", False) is True:
  6899. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6900. else:
  6901. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6902. if name:
  6903. filenames = [name]
  6904. else:
  6905. try:
  6906. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6907. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6908. except TypeError:
  6909. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6910. if len(filenames) == 0:
  6911. if silent is False:
  6912. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6913. else:
  6914. for filename in filenames:
  6915. if filename != '':
  6916. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6917. def on_filerunscript(self, name=None, silent=False):
  6918. """
  6919. File menu callback for loading and running a TCL script.
  6920. :param silent: if True will not display status messages
  6921. :param name: name of a Tcl script file to be run by FlatCAM
  6922. :return: None
  6923. """
  6924. self.defaults.report_usage("on_filerunscript")
  6925. App.log.debug("on_file_runscript()")
  6926. if name:
  6927. filename = name
  6928. if self.cmd_line_headless != 1:
  6929. self.splash.showMessage('%s: %ssec\n%s' %
  6930. (_("Canvas initialization started.\n"
  6931. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6932. _("Executing ScriptObject file.")
  6933. ),
  6934. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6935. color=QtGui.QColor("gray"))
  6936. else:
  6937. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6938. "All Files (*.*)"
  6939. try:
  6940. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6941. directory=self.get_last_folder(), filter=_filter_)
  6942. except TypeError:
  6943. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6944. # The Qt methods above will return a QString which can cause problems later.
  6945. # So far json.dump() will fail to serialize it.
  6946. filename = str(filename)
  6947. if filename == "":
  6948. if silent is False:
  6949. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6950. else:
  6951. if self.cmd_line_headless != 1:
  6952. if self.ui.shell_dock.isHidden():
  6953. self.ui.shell_dock.show()
  6954. try:
  6955. with open(filename, "r") as tcl_script:
  6956. cmd_line_shellfile_content = tcl_script.read()
  6957. if self.cmd_line_headless != 1:
  6958. self.shell.exec_command(cmd_line_shellfile_content)
  6959. else:
  6960. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6961. if silent is False:
  6962. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6963. except Exception as e:
  6964. log.debug("App.on_filerunscript() -> %s" % str(e))
  6965. sys.exit(2)
  6966. def on_file_saveproject(self, silent=False):
  6967. """
  6968. Callback for menu item File->Save Project. Saves the project to
  6969. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6970. if set to None. The project is saved by calling ``self.save_project()``.
  6971. :param silent: if True will not display status messages
  6972. :return: None
  6973. """
  6974. self.defaults.report_usage("on_file_saveproject")
  6975. if self.project_filename is None:
  6976. self.on_file_saveprojectas()
  6977. else:
  6978. self.worker_task.emit({'fcn': self.save_project,
  6979. 'params': [self.project_filename, silent]})
  6980. if self.defaults["global_open_style"] is False:
  6981. self.file_opened.emit("project", self.project_filename)
  6982. self.file_saved.emit("project", self.project_filename)
  6983. self.set_ui_title(name=self.project_filename)
  6984. self.should_we_save = False
  6985. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6986. """
  6987. Callback for menu item File->Save Project As... Opens a file
  6988. chooser and saves the project to the given file via
  6989. ``self.save_project()``.
  6990. :param make_copy if to be create a copy of the project; boolean
  6991. :param use_thread: if to be run in a separate thread; boolean
  6992. :param quit_action: if to be followed by quiting the application; boolean
  6993. :return: None
  6994. """
  6995. self.defaults.report_usage("on_file_saveprojectas")
  6996. self.date = str(datetime.today()).rpartition('.')[0]
  6997. self.date = ''.join(c for c in self.date if c not in ':-')
  6998. self.date = self.date.replace(' ', '_')
  6999. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7000. try:
  7001. filename, _f = FCFileSaveDialog.get_saved_filename(
  7002. caption=_("Save Project As ..."),
  7003. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7004. proj=_("Project")),
  7005. filter=filter_
  7006. )
  7007. except TypeError:
  7008. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7009. filename = str(filename)
  7010. if filename == '':
  7011. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7012. return
  7013. if use_thread is True:
  7014. self.worker_task.emit({'fcn': self.save_project,
  7015. 'params': [filename, quit_action]})
  7016. else:
  7017. self.save_project(filename, quit_action)
  7018. # self.save_project(filename)
  7019. if self.defaults["global_open_style"] is False:
  7020. self.file_opened.emit("project", filename)
  7021. self.file_saved.emit("project", filename)
  7022. if not make_copy:
  7023. self.project_filename = filename
  7024. self.set_ui_title(name=self.project_filename)
  7025. self.should_we_save = False
  7026. def on_file_save_objects_pdf(self, use_thread=True):
  7027. self.date = str(datetime.today()).rpartition('.')[0]
  7028. self.date = ''.join(c for c in self.date if c not in ':-')
  7029. self.date = self.date.replace(' ', '_')
  7030. try:
  7031. obj_selection = self.collection.get_selected()
  7032. if len(obj_selection) == 1:
  7033. obj_name = str(obj_selection[0].options['name'])
  7034. else:
  7035. obj_name = _("FlatCAM objects print")
  7036. except AttributeError as err:
  7037. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7038. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7039. return
  7040. if not obj_selection:
  7041. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7042. return
  7043. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7044. try:
  7045. filename, _f = FCFileSaveDialog.get_saved_filename(
  7046. caption=_("Save Object as PDF ..."),
  7047. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7048. obj_name=obj_name,
  7049. date=self.date),
  7050. filter=filter_
  7051. )
  7052. except TypeError:
  7053. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7054. filename = str(filename)
  7055. if filename == '':
  7056. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7057. return
  7058. if use_thread is True:
  7059. self.proc_container.new(_("Printing PDF ... Please wait."))
  7060. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7061. else:
  7062. self.save_pdf(filename, obj_selection)
  7063. # self.save_project(filename)
  7064. if self.defaults["global_open_style"] is False:
  7065. self.file_opened.emit("pdf", filename)
  7066. self.file_saved.emit("pdf", filename)
  7067. def save_pdf(self, file_name, obj_selection):
  7068. p_size = self.defaults['global_workspaceT']
  7069. orientation = self.defaults['global_workspace_orientation']
  7070. color = 'black'
  7071. transparency_level = 1.0
  7072. self.pagesize = {}
  7073. self.pagesize.update(
  7074. {
  7075. 'Bounds': None,
  7076. 'A0': (841 * mm, 1189 * mm),
  7077. 'A1': (594 * mm, 841 * mm),
  7078. 'A2': (420 * mm, 594 * mm),
  7079. 'A3': (297 * mm, 420 * mm),
  7080. 'A4': (210 * mm, 297 * mm),
  7081. 'A5': (148 * mm, 210 * mm),
  7082. 'A6': (105 * mm, 148 * mm),
  7083. 'A7': (74 * mm, 105 * mm),
  7084. 'A8': (52 * mm, 74 * mm),
  7085. 'A9': (37 * mm, 52 * mm),
  7086. 'A10': (26 * mm, 37 * mm),
  7087. 'B0': (1000 * mm, 1414 * mm),
  7088. 'B1': (707 * mm, 1000 * mm),
  7089. 'B2': (500 * mm, 707 * mm),
  7090. 'B3': (353 * mm, 500 * mm),
  7091. 'B4': (250 * mm, 353 * mm),
  7092. 'B5': (176 * mm, 250 * mm),
  7093. 'B6': (125 * mm, 176 * mm),
  7094. 'B7': (88 * mm, 125 * mm),
  7095. 'B8': (62 * mm, 88 * mm),
  7096. 'B9': (44 * mm, 62 * mm),
  7097. 'B10': (31 * mm, 44 * mm),
  7098. 'C0': (917 * mm, 1297 * mm),
  7099. 'C1': (648 * mm, 917 * mm),
  7100. 'C2': (458 * mm, 648 * mm),
  7101. 'C3': (324 * mm, 458 * mm),
  7102. 'C4': (229 * mm, 324 * mm),
  7103. 'C5': (162 * mm, 229 * mm),
  7104. 'C6': (114 * mm, 162 * mm),
  7105. 'C7': (81 * mm, 114 * mm),
  7106. 'C8': (57 * mm, 81 * mm),
  7107. 'C9': (40 * mm, 57 * mm),
  7108. 'C10': (28 * mm, 40 * mm),
  7109. # American paper sizes
  7110. 'LETTER': (8.5 * inch, 11 * inch),
  7111. 'LEGAL': (8.5 * inch, 14 * inch),
  7112. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7113. # From https://en.wikipedia.org/wiki/Paper_size
  7114. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7115. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7116. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7117. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7118. 'LEDGER': (17 * inch, 11 * inch),
  7119. }
  7120. )
  7121. exported_svg = []
  7122. for obj in obj_selection:
  7123. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7124. scale_factor_x=None, scale_factor_y=None,
  7125. skew_factor_x=None, skew_factor_y=None,
  7126. mirror=None)
  7127. if obj.kind.lower() == 'gerber':
  7128. # color = self.defaults["gerber_plot_fill"][:-2]
  7129. color = obj.fill_color[:-2]
  7130. elif obj.kind.lower() == 'excellon':
  7131. color = '#C40000'
  7132. elif obj.kind.lower() == 'geometry':
  7133. color = self.defaults["global_draw_color"]
  7134. # Change the attributes of the exported SVG
  7135. # We don't need stroke-width
  7136. # We set opacity to maximum
  7137. # We set the colour to WHITE
  7138. root = ET.fromstring(svg_obj)
  7139. for child in root:
  7140. child.set('fill', str(color))
  7141. child.set('opacity', str(transparency_level))
  7142. child.set('stroke', str(color))
  7143. exported_svg.append(ET.tostring(root))
  7144. xmin = Inf
  7145. ymin = Inf
  7146. xmax = -Inf
  7147. ymax = -Inf
  7148. for obj in obj_selection:
  7149. try:
  7150. gxmin, gymin, gxmax, gymax = obj.bounds()
  7151. xmin = min([xmin, gxmin])
  7152. ymin = min([ymin, gymin])
  7153. xmax = max([xmax, gxmax])
  7154. ymax = max([ymax, gymax])
  7155. except Exception as e:
  7156. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7157. # Determine bounding area for svg export
  7158. bounds = [xmin, ymin, xmax, ymax]
  7159. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7160. # This contain the measure units
  7161. uom = obj_selection[0].units.lower()
  7162. # Define a boundary around SVG of about 1.0mm (~39mils)
  7163. if uom in "mm":
  7164. boundary = 1.0
  7165. else:
  7166. boundary = 0.0393701
  7167. # Convert everything to strings for use in the xml doc
  7168. svgwidth = str(size[0] + (2 * boundary))
  7169. svgheight = str(size[1] + (2 * boundary))
  7170. minx = str(bounds[0] - boundary)
  7171. miny = str(bounds[1] + boundary + size[1])
  7172. # Add a SVG Header and footer to the svg output from shapely
  7173. # The transform flips the Y Axis so that everything renders
  7174. # properly within svg apps such as inkscape
  7175. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7176. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7177. svg_header += 'width="' + svgwidth + uom + '" '
  7178. svg_header += 'height="' + svgheight + uom + '" '
  7179. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7180. svg_header += '>'
  7181. svg_header += '<g transform="scale(1,-1)">'
  7182. svg_footer = '</g> </svg>'
  7183. svg_elem = str(svg_header)
  7184. for svg_item in exported_svg:
  7185. svg_elem += str(svg_item)
  7186. svg_elem += str(svg_footer)
  7187. # Parse the xml through a xml parser just to add line feeds
  7188. # and to make it look more pretty for the output
  7189. doc = parse_xml_string(svg_elem)
  7190. doc_final = doc.toprettyxml()
  7191. try:
  7192. if self.defaults['units'].upper() == 'IN':
  7193. unit = inch
  7194. else:
  7195. unit = mm
  7196. doc_final = StringIO(doc_final)
  7197. drawing = svg2rlg(doc_final)
  7198. if p_size == 'Bounds':
  7199. renderPDF.drawToFile(drawing, file_name)
  7200. else:
  7201. if orientation == 'p':
  7202. page_size = portrait(self.pagesize[p_size])
  7203. else:
  7204. page_size = landscape(self.pagesize[p_size])
  7205. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7206. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7207. renderPDF.draw(drawing, my_canvas, 0, 0)
  7208. my_canvas.save()
  7209. except Exception as e:
  7210. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7211. return 'fail'
  7212. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7213. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7214. """
  7215. Exports a Geometry Object to an SVG file.
  7216. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7217. :param filename: Path to the SVG file to save to.
  7218. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7219. :return:
  7220. """
  7221. self.defaults.report_usage("export_svg()")
  7222. if filename is None:
  7223. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7224. is not None else self.defaults["global_last_folder"]
  7225. self.log.debug("export_svg()")
  7226. try:
  7227. obj = self.collection.get_by_name(str(obj_name))
  7228. except Exception:
  7229. # TODO: The return behavior has not been established... should raise exception?
  7230. return "Could not retrieve object: %s" % obj_name
  7231. with self.proc_container.new(_("Exporting SVG")) as proc:
  7232. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7233. # Determine bounding area for svg export
  7234. bounds = obj.bounds()
  7235. size = obj.size()
  7236. # Convert everything to strings for use in the xml doc
  7237. svgwidth = str(size[0])
  7238. svgheight = str(size[1])
  7239. minx = str(bounds[0])
  7240. miny = str(bounds[1] - size[1])
  7241. uom = obj.units.lower()
  7242. # Add a SVG Header and footer to the svg output from shapely
  7243. # The transform flips the Y Axis so that everything renders
  7244. # properly within svg apps such as inkscape
  7245. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7246. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7247. svg_header += 'width="' + svgwidth + uom + '" '
  7248. svg_header += 'height="' + svgheight + uom + '" '
  7249. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7250. svg_header += '<g transform="scale(1,-1)">'
  7251. svg_footer = '</g> </svg>'
  7252. svg_elem = svg_header + exported_svg + svg_footer
  7253. # Parse the xml through a xml parser just to add line feeds
  7254. # and to make it look more pretty for the output
  7255. svgcode = parse_xml_string(svg_elem)
  7256. svgcode = svgcode.toprettyxml()
  7257. try:
  7258. with open(filename, 'w') as fp:
  7259. fp.write(svgcode)
  7260. except PermissionError:
  7261. self.inform.emit('[WARNING] %s' %
  7262. _("Permission denied, saving not possible.\n"
  7263. "Most likely another app is holding the file open and not accessible."))
  7264. return 'fail'
  7265. if self.defaults["global_open_style"] is False:
  7266. self.file_opened.emit("SVG", filename)
  7267. self.file_saved.emit("SVG", filename)
  7268. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7269. def save_source_file(self, obj_name, filename, use_thread=True):
  7270. """
  7271. Exports a FlatCAM Object to an Gerber/Excellon file.
  7272. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7273. :param filename: Path to the Gerber file to save to.
  7274. :param use_thread: if to be run in a separate thread
  7275. :return:
  7276. """
  7277. self.defaults.report_usage("save source file()")
  7278. if filename is None:
  7279. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7280. is not None else self.defaults["global_last_folder"]
  7281. self.log.debug("save source file()")
  7282. obj = self.collection.get_by_name(obj_name)
  7283. file_string = StringIO(obj.source_file)
  7284. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7285. if file_string.getvalue() == '':
  7286. self.inform.emit('[ERROR_NOTCL] %s' %
  7287. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7288. return 'fail'
  7289. try:
  7290. with open(filename, 'w') as file:
  7291. file.writelines('G04*\n')
  7292. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7293. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7294. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7295. file.writelines('G04 Created on : %s*\n' % time_string)
  7296. for line in file_string:
  7297. file.writelines(line)
  7298. except PermissionError:
  7299. self.inform.emit('[WARNING] %s' %
  7300. _("Permission denied, saving not possible.\n"
  7301. "Most likely another app is holding the file open and not accessible."))
  7302. return 'fail'
  7303. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7304. """
  7305. Exports a Excellon Object to an Excellon file.
  7306. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7307. :param filename: Path to the Excellon file to save to.
  7308. :param local_use:
  7309. :param use_thread: if to be run in a separate thread
  7310. :return:
  7311. """
  7312. self.defaults.report_usage("export_excellon()")
  7313. if filename is None:
  7314. if self.defaults["global_last_save_folder"]:
  7315. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7316. else:
  7317. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7318. self.log.debug("export_excellon()")
  7319. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7320. self.defaults["excellon_exp_decimals"]
  7321. )
  7322. if local_use is None:
  7323. try:
  7324. obj = self.collection.get_by_name(str(obj_name))
  7325. except Exception:
  7326. return "Could not retrieve object: %s" % obj_name
  7327. else:
  7328. obj = local_use
  7329. if not isinstance(obj, ExcellonObject):
  7330. self.inform.emit('[ERROR_NOTCL] %s' %
  7331. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7332. return
  7333. # updated units
  7334. eunits = self.defaults["excellon_exp_units"]
  7335. ewhole = self.defaults["excellon_exp_integer"]
  7336. efract = self.defaults["excellon_exp_decimals"]
  7337. ezeros = self.defaults["excellon_exp_zeros"]
  7338. eformat = self.defaults["excellon_exp_format"]
  7339. slot_type = self.defaults["excellon_exp_slot_type"]
  7340. fc_units = self.defaults['units'].upper()
  7341. if fc_units == 'MM':
  7342. factor = 1 if eunits == 'METRIC' else 0.03937
  7343. else:
  7344. factor = 25.4 if eunits == 'METRIC' else 1
  7345. def make_excellon():
  7346. try:
  7347. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7348. header = 'M48\n'
  7349. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7350. (str(self.version), str(self.version_date))
  7351. header += ';Filename: %s' % str(obj_name) + '\n'
  7352. header += ';Created on : %s' % time_str + '\n'
  7353. if eformat == 'dec':
  7354. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7355. header += eunits + '\n'
  7356. for tool in obj.tools:
  7357. if eunits == 'METRIC':
  7358. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7359. tool=str(tool),
  7360. dec=2)
  7361. else:
  7362. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7363. tool=str(tool),
  7364. dec=4)
  7365. else:
  7366. if ezeros == 'LZ':
  7367. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7368. form='ndec', e_zeros='LZ', factor=factor,
  7369. slot_type=slot_type)
  7370. header += '%s,%s\n' % (eunits, 'LZ')
  7371. header += format_exc
  7372. for tool in obj.tools:
  7373. if eunits == 'METRIC':
  7374. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7375. tool=str(tool),
  7376. dec=2)
  7377. else:
  7378. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7379. tool=str(tool),
  7380. dec=4)
  7381. else:
  7382. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7383. form='ndec', e_zeros='TZ', factor=factor,
  7384. slot_type=slot_type)
  7385. header += '%s,%s\n' % (eunits, 'TZ')
  7386. header += format_exc
  7387. for tool in obj.tools:
  7388. if eunits == 'METRIC':
  7389. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7390. tool=str(tool),
  7391. dec=2)
  7392. else:
  7393. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7394. tool=str(tool),
  7395. dec=4)
  7396. header += '%\n'
  7397. footer = 'M30\n'
  7398. exported_excellon = header
  7399. exported_excellon += excellon_code
  7400. exported_excellon += footer
  7401. if local_use is None:
  7402. try:
  7403. with open(filename, 'w') as fp:
  7404. fp.write(exported_excellon)
  7405. except PermissionError:
  7406. self.inform.emit('[WARNING] %s' %
  7407. _("Permission denied, saving not possible.\n"
  7408. "Most likely another app is holding the file open and not accessible."))
  7409. return 'fail'
  7410. if self.defaults["global_open_style"] is False:
  7411. self.file_opened.emit("Excellon", filename)
  7412. self.file_saved.emit("Excellon", filename)
  7413. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7414. else:
  7415. return exported_excellon
  7416. except Exception as e:
  7417. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7418. return 'fail'
  7419. if use_thread is True:
  7420. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7421. def job_thread_exc(app_obj):
  7422. ret = make_excellon()
  7423. if ret == 'fail':
  7424. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7425. return
  7426. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7427. else:
  7428. eret = make_excellon()
  7429. if eret == 'fail':
  7430. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7431. return 'fail'
  7432. if local_use is not None:
  7433. return eret
  7434. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7435. """
  7436. Exports a Gerber Object to an Gerber file.
  7437. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7438. :param filename: Path to the Gerber file to save to.
  7439. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7440. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7441. :param use_thread: if to be run in a separate thread
  7442. :return:
  7443. """
  7444. self.defaults.report_usage("export_gerber()")
  7445. if filename is None:
  7446. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7447. is not None else self.defaults["global_last_folder"]
  7448. self.log.debug("export_gerber()")
  7449. if local_use is None:
  7450. try:
  7451. obj = self.collection.get_by_name(str(obj_name))
  7452. except Exception:
  7453. return "Could not retrieve object: %s" % obj_name
  7454. else:
  7455. obj = local_use
  7456. # updated units
  7457. gunits = self.defaults["gerber_exp_units"]
  7458. gwhole = self.defaults["gerber_exp_integer"]
  7459. gfract = self.defaults["gerber_exp_decimals"]
  7460. gzeros = self.defaults["gerber_exp_zeros"]
  7461. fc_units = self.defaults['units'].upper()
  7462. if fc_units == 'MM':
  7463. factor = 1 if gunits == 'MM' else 0.03937
  7464. else:
  7465. factor = 25.4 if gunits == 'MM' else 1
  7466. def make_gerber():
  7467. try:
  7468. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7469. header = 'G04*\n'
  7470. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7471. (str(self.version), str(self.version_date))
  7472. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7473. header += 'G04 Created on : %s*' % time_str + '\n'
  7474. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7475. header += "%MO{units}*%\n".format(units=gunits)
  7476. for apid in obj.apertures:
  7477. if obj.apertures[apid]['type'] == 'C':
  7478. header += "%ADD{apid}{type},{size}*%\n".format(
  7479. apid=str(apid),
  7480. type='C',
  7481. size=(factor * obj.apertures[apid]['size'])
  7482. )
  7483. elif obj.apertures[apid]['type'] == 'R':
  7484. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7485. apid=str(apid),
  7486. type='R',
  7487. width=(factor * obj.apertures[apid]['width']),
  7488. height=(factor * obj.apertures[apid]['height'])
  7489. )
  7490. elif obj.apertures[apid]['type'] == 'O':
  7491. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7492. apid=str(apid),
  7493. type='O',
  7494. width=(factor * obj.apertures[apid]['width']),
  7495. height=(factor * obj.apertures[apid]['height'])
  7496. )
  7497. header += '\n'
  7498. # obsolete units but some software may need it
  7499. if gunits == 'IN':
  7500. header += 'G70*\n'
  7501. else:
  7502. header += 'G71*\n'
  7503. # Absolute Mode
  7504. header += 'G90*\n'
  7505. header += 'G01*\n'
  7506. # positive polarity
  7507. header += '%LPD*%\n'
  7508. footer = 'M02*\n'
  7509. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7510. exported_gerber = header
  7511. exported_gerber += gerber_code
  7512. exported_gerber += footer
  7513. if local_use is None:
  7514. try:
  7515. with open(filename, 'w') as fp:
  7516. fp.write(exported_gerber)
  7517. except PermissionError:
  7518. self.inform.emit('[WARNING] %s' %
  7519. _("Permission denied, saving not possible.\n"
  7520. "Most likely another app is holding the file open and not accessible."))
  7521. return 'fail'
  7522. if self.defaults["global_open_style"] is False:
  7523. self.file_opened.emit("Gerber", filename)
  7524. self.file_saved.emit("Gerber", filename)
  7525. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7526. else:
  7527. return exported_gerber
  7528. except Exception as e:
  7529. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7530. return 'fail'
  7531. if use_thread is True:
  7532. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7533. def job_thread_grb(app_obj):
  7534. ret = make_gerber()
  7535. if ret == 'fail':
  7536. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7537. return
  7538. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7539. else:
  7540. gret = make_gerber()
  7541. if gret == 'fail':
  7542. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7543. return 'fail'
  7544. if local_use is not None:
  7545. return gret
  7546. def export_dxf(self, obj_name, filename, use_thread=True):
  7547. """
  7548. Exports a Geometry Object to an DXF file.
  7549. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7550. :param filename: Path to the DXF file to save to.
  7551. :param use_thread: if to be run in a separate thread
  7552. :return:
  7553. """
  7554. self.defaults.report_usage("export_dxf()")
  7555. if filename is None:
  7556. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7557. is not None else self.defaults["global_last_folder"]
  7558. self.log.debug("export_dxf()")
  7559. try:
  7560. obj = self.collection.get_by_name(str(obj_name))
  7561. except Exception:
  7562. # TODO: The return behavior has not been established... should raise exception?
  7563. return "Could not retrieve object: %s" % obj_name
  7564. def make_dxf():
  7565. try:
  7566. dxf_code = obj.export_dxf()
  7567. dxf_code.saveas(filename)
  7568. if self.defaults["global_open_style"] is False:
  7569. self.file_opened.emit("DXF", filename)
  7570. self.file_saved.emit("DXF", filename)
  7571. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7572. except Exception:
  7573. return 'fail'
  7574. if use_thread is True:
  7575. with self.proc_container.new(_("Exporting DXF")) as proc:
  7576. def job_thread_exc(app_obj):
  7577. ret_dxf_val = make_dxf()
  7578. if ret_dxf_val == 'fail':
  7579. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7580. return
  7581. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7582. else:
  7583. ret = make_dxf()
  7584. if ret == 'fail':
  7585. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7586. return
  7587. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7588. """
  7589. Adds a new Geometry Object to the projects and populates
  7590. it with shapes extracted from the SVG file.
  7591. :param plot: If True then the resulting object will be plotted on canvas
  7592. :param filename: Path to the SVG file.
  7593. :param geo_type: Type of FlatCAM object that will be created from SVG
  7594. :param outname: The name given to the resulting FlatCAM object
  7595. :return:
  7596. """
  7597. self.defaults.report_usage("import_svg()")
  7598. log.debug("App.import_svg()")
  7599. obj_type = ""
  7600. if geo_type is None or geo_type == "geometry":
  7601. obj_type = "geometry"
  7602. elif geo_type == "gerber":
  7603. obj_type = "gerber"
  7604. else:
  7605. self.inform.emit('[ERROR_NOTCL] %s' %
  7606. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7607. return
  7608. units = self.defaults['units'].upper()
  7609. def obj_init(geo_obj, app_obj):
  7610. geo_obj.import_svg(filename, obj_type, units=units)
  7611. geo_obj.multigeo = False
  7612. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7613. with self.proc_container.new(_("Importing SVG")) as proc:
  7614. # Object name
  7615. name = outname or filename.split('/')[-1].split('\\')[-1]
  7616. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7617. if ret == 'fail':
  7618. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7619. return 'fail'
  7620. # Register recent file
  7621. self.file_opened.emit("svg", filename)
  7622. # GUI feedback
  7623. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7624. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7625. """
  7626. Adds a new Geometry Object to the projects and populates
  7627. it with shapes extracted from the DXF file.
  7628. :param filename: Path to the DXF file.
  7629. :param geo_type: Type of FlatCAM object that will be created from DXF
  7630. :param outname: Name for the imported Geometry
  7631. :param plot: If True then the resulting object will be plotted on canvas
  7632. :return:
  7633. """
  7634. self.defaults.report_usage("import_dxf()")
  7635. obj_type = ""
  7636. if geo_type is None or geo_type == "geometry":
  7637. obj_type = "geometry"
  7638. elif geo_type == "gerber":
  7639. obj_type = geo_type
  7640. else:
  7641. self.inform.emit('[ERROR_NOTCL] %s' %
  7642. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7643. return
  7644. units = self.defaults['units'].upper()
  7645. def obj_init(geo_obj, app_obj):
  7646. geo_obj.import_dxf(filename, obj_type, units=units)
  7647. geo_obj.multigeo = False
  7648. with self.proc_container.new(_("Importing DXF")):
  7649. # Object name
  7650. name = outname or filename.split('/')[-1].split('\\')[-1]
  7651. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7652. if ret == 'fail':
  7653. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7654. return 'fail'
  7655. # Register recent file
  7656. self.file_opened.emit("dxf", filename)
  7657. # GUI feedback
  7658. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7659. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7660. """
  7661. Opens a Gerber file, parses it and creates a new object for
  7662. it in the program. Thread-safe.
  7663. :param outname: Name of the resulting object. None causes the
  7664. name to be that of the file. Str.
  7665. :param filename: Gerber file filename
  7666. :type filename: str
  7667. :param plot: boolean, to plot or not the resulting object
  7668. :param from_tcl: True if run from Tcl Shell
  7669. :return: None
  7670. """
  7671. # How the object should be initialized
  7672. def obj_init(gerber_obj, app_obj):
  7673. assert isinstance(gerber_obj, GerberObject), \
  7674. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7675. # Opening the file happens here
  7676. try:
  7677. gerber_obj.parse_file(filename)
  7678. except IOError:
  7679. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7680. return "fail"
  7681. except ParseError as err:
  7682. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7683. app_obj.log.error(str(err))
  7684. return "fail"
  7685. except Exception as e:
  7686. log.debug("App.open_gerber() --> %s" % str(e))
  7687. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7688. msg += traceback.format_exc()
  7689. app_obj.inform.emit(msg)
  7690. return "fail"
  7691. if gerber_obj.is_empty():
  7692. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7693. _("Object is not Gerber file or empty. Aborting object creation."))
  7694. return "fail"
  7695. App.log.debug("open_gerber()")
  7696. with self.proc_container.new(_("Opening Gerber")):
  7697. # Object name
  7698. name = outname or filename.split('/')[-1].split('\\')[-1]
  7699. # # ## Object creation # ##
  7700. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7701. if ret_val == 'fail':
  7702. if from_tcl:
  7703. filename = self.defaults['global_tcl_path'] + '/' + name
  7704. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7705. if ret_val == 'fail':
  7706. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7707. return 'fail'
  7708. # Register recent file
  7709. self.file_opened.emit("gerber", filename)
  7710. # GUI feedback
  7711. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7712. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7713. """
  7714. Opens an Excellon file, parses it and creates a new object for
  7715. it in the program. Thread-safe.
  7716. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7717. :param filename: Excellon file filename
  7718. :type filename: str
  7719. :param plot: boolean, to plot or not the resulting object
  7720. :param from_tcl: True if run from Tcl Shell
  7721. :return: None
  7722. """
  7723. App.log.debug("open_excellon()")
  7724. # How the object should be initialized
  7725. def obj_init(excellon_obj, app_obj):
  7726. try:
  7727. ret = excellon_obj.parse_file(filename=filename)
  7728. if ret == "fail":
  7729. log.debug("Excellon parsing failed.")
  7730. self.inform.emit('[ERROR_NOTCL] %s' %
  7731. _("This is not Excellon file."))
  7732. return "fail"
  7733. except IOError:
  7734. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7735. (_("Cannot open file"), filename))
  7736. log.debug("Could not open Excellon object.")
  7737. return "fail"
  7738. except Exception:
  7739. msg = '[ERROR_NOTCL] %s' % \
  7740. _("An internal error has occurred. See shell.\n")
  7741. msg += traceback.format_exc()
  7742. app_obj.inform.emit(msg)
  7743. return "fail"
  7744. ret = excellon_obj.create_geometry()
  7745. if ret == 'fail':
  7746. log.debug("Could not create geometry for Excellon object.")
  7747. return "fail"
  7748. for tool in excellon_obj.tools:
  7749. if excellon_obj.tools[tool]['solid_geometry']:
  7750. return
  7751. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7752. return "fail"
  7753. with self.proc_container.new(_("Opening Excellon.")):
  7754. # Object name
  7755. name = outname or filename.split('/')[-1].split('\\')[-1]
  7756. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7757. if ret_val == 'fail':
  7758. if from_tcl:
  7759. filename = self.defaults['global_tcl_path'] + '/' + name
  7760. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7761. if ret_val == 'fail':
  7762. self.inform.emit('[ERROR_NOTCL] %s' %
  7763. _('Open Excellon file failed. Probable not an Excellon file.'))
  7764. return
  7765. # Register recent file
  7766. self.file_opened.emit("excellon", filename)
  7767. # GUI feedback
  7768. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7769. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7770. """
  7771. Opens a G-gcode file, parses it and creates a new object for
  7772. it in the program. Thread-safe.
  7773. :param filename: G-code file filename
  7774. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7775. :param force_parsing:
  7776. :param plot: If True plot the object on canvas
  7777. :param from_tcl: True if run from Tcl Shell
  7778. :return: None
  7779. """
  7780. App.log.debug("open_gcode()")
  7781. # How the object should be initialized
  7782. def obj_init(job_obj, app_obj_):
  7783. """
  7784. :param job_obj: the resulting object
  7785. :type app_obj_: App
  7786. """
  7787. assert isinstance(app_obj_, App), \
  7788. "Initializer expected App, got %s" % type(app_obj_)
  7789. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7790. try:
  7791. f = open(filename)
  7792. gcode = f.read()
  7793. f.close()
  7794. except IOError:
  7795. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7796. return "fail"
  7797. job_obj.gcode = gcode
  7798. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7799. if gcode_ret == "fail":
  7800. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7801. return "fail"
  7802. job_obj.create_geometry()
  7803. with self.proc_container.new(_("Opening G-Code.")):
  7804. # Object name
  7805. name = outname or filename.split('/')[-1].split('\\')[-1]
  7806. # New object creation and file processing
  7807. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7808. if ret_val == 'fail':
  7809. if from_tcl:
  7810. filename = self.defaults['global_tcl_path'] + '/' + name
  7811. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7812. if ret_val == 'fail':
  7813. self.inform.emit('[ERROR_NOTCL] %s' %
  7814. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7815. "Try to load it from File menu.\n "
  7816. "Attempting to create a FlatCAM CNCJob Object from "
  7817. "G-Code file failed during processing"))
  7818. return "fail"
  7819. # Register recent file
  7820. self.file_opened.emit("cncjob", filename)
  7821. # GUI feedback
  7822. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7823. def open_hpgl2(self, filename, outname=None):
  7824. """
  7825. Opens a HPGL2 file, parses it and creates a new object for
  7826. it in the program. Thread-safe.
  7827. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7828. :param filename: HPGL2 file filename
  7829. :return: None
  7830. """
  7831. filename = filename
  7832. # How the object should be initialized
  7833. def obj_init(geo_obj, app_obj):
  7834. assert isinstance(geo_obj, GeometryObject), \
  7835. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7836. # Opening the file happens here
  7837. obj = HPGL2(self)
  7838. try:
  7839. HPGL2.parse_file(obj, filename)
  7840. except IOError:
  7841. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7842. return "fail"
  7843. except ParseError as err:
  7844. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7845. app_obj.log.error(str(err))
  7846. return "fail"
  7847. except Exception as e:
  7848. log.debug("App.open_hpgl2() --> %s" % str(e))
  7849. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7850. msg += traceback.format_exc()
  7851. app_obj.inform.emit(msg)
  7852. return "fail"
  7853. geo_obj.multigeo = True
  7854. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7855. geo_obj.tools = deepcopy(obj.tools)
  7856. geo_obj.source_file = deepcopy(obj.source_file)
  7857. del obj
  7858. if not geo_obj.solid_geometry:
  7859. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7860. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7861. return "fail"
  7862. App.log.debug("open_hpgl2()")
  7863. with self.proc_container.new(_("Opening HPGL2")):
  7864. # Object name
  7865. name = outname or filename.split('/')[-1].split('\\')[-1]
  7866. # # ## Object creation # ##
  7867. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7868. if ret == 'fail':
  7869. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7870. return 'fail'
  7871. # Register recent file
  7872. self.file_opened.emit("geometry", filename)
  7873. # GUI feedback
  7874. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7875. def open_script(self, filename, outname=None, silent=False):
  7876. """
  7877. Opens a Script file, parses it and creates a new object for
  7878. it in the program. Thread-safe.
  7879. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7880. :param filename: Script file filename
  7881. :param silent: If True there will be no messages printed to StatusBar
  7882. :return: None
  7883. """
  7884. def obj_init(script_obj, app_obj):
  7885. assert isinstance(script_obj, ScriptObject), \
  7886. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7887. if silent is False:
  7888. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7889. try:
  7890. script_obj.parse_file(filename)
  7891. except IOError:
  7892. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7893. return "fail"
  7894. except ParseError as err:
  7895. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7896. app_obj.log.error(str(err))
  7897. return "fail"
  7898. except Exception as e:
  7899. log.debug("App.open_script() -> %s" % str(e))
  7900. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7901. msg += traceback.format_exc()
  7902. app_obj.inform.emit(msg)
  7903. return "fail"
  7904. App.log.debug("open_script()")
  7905. with self.proc_container.new(_("Opening TCL Script...")):
  7906. # Object name
  7907. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7908. # Object creation
  7909. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7910. if ret_val == 'fail':
  7911. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7912. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7913. if ret_val == 'fail':
  7914. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7915. return 'fail'
  7916. # Register recent file
  7917. self.file_opened.emit("script", filename)
  7918. # GUI feedback
  7919. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7920. def open_config_file(self, filename, run_from_arg=None):
  7921. """
  7922. Loads a config file from the specified file.
  7923. :param filename: Name of the file from which to load.
  7924. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7925. :return: None
  7926. """
  7927. App.log.debug("Opening config file: " + filename)
  7928. if run_from_arg:
  7929. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7930. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7931. _("Opening FlatCAM Config file.")),
  7932. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7933. color=QtGui.QColor("gray"))
  7934. # # add the tab if it was closed
  7935. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7936. # # first clear previous text in text editor (if any)
  7937. # self.ui.text_editor_tab.code_editor.clear()
  7938. #
  7939. # # Switch plot_area to CNCJob tab
  7940. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7941. # close the Code editor if already open
  7942. if self.toggle_codeeditor:
  7943. self.on_toggle_code_editor()
  7944. self.on_toggle_code_editor()
  7945. try:
  7946. if filename:
  7947. f = QtCore.QFile(filename)
  7948. if f.open(QtCore.QIODevice.ReadOnly):
  7949. stream = QtCore.QTextStream(f)
  7950. code_edited = stream.readAll()
  7951. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7952. f.close()
  7953. except IOError:
  7954. App.log.error("Failed to open config file: %s" % filename)
  7955. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7956. (_("Failed to open config file"), filename))
  7957. return
  7958. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7959. """
  7960. Loads a project from the specified file.
  7961. 1) Loads and parses file
  7962. 2) Registers the file as recently opened.
  7963. 3) Calls on_file_new()
  7964. 4) Updates options
  7965. 5) Calls new_object() with the object's from_dict() as init method.
  7966. 6) Calls plot_all() if plot=True
  7967. :param filename: Name of the file from which to load.
  7968. :param run_from_arg: True if run for arguments
  7969. :param plot: If True plot all objects in the project
  7970. :param cli: Run from command line
  7971. :param from_tcl: True if run from Tcl Sehll
  7972. :return: None
  7973. """
  7974. App.log.debug("Opening project: " + filename)
  7975. # block autosaving while a project is loaded
  7976. self.block_autosave = True
  7977. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7978. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7979. if cli is None:
  7980. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7981. if run_from_arg:
  7982. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7983. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7984. _("Opening FlatCAM Project file.")),
  7985. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7986. color=QtGui.QColor("gray"))
  7987. # Open and parse an uncompressed Project file
  7988. try:
  7989. f = open(filename, 'r')
  7990. except IOError:
  7991. if from_tcl:
  7992. name = filename.split('/')[-1].split('\\')[-1]
  7993. filename = self.defaults['global_tcl_path'] + '/' + name
  7994. try:
  7995. f = open(filename, 'r')
  7996. except IOError:
  7997. log.error("Failed to open project file: %s" % filename)
  7998. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7999. return
  8000. else:
  8001. log.error("Failed to open project file: %s" % filename)
  8002. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8003. return
  8004. try:
  8005. d = json.load(f, object_hook=dict2obj)
  8006. except Exception as e:
  8007. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8008. (filename, str(e)))
  8009. f.close()
  8010. # Open and parse a compressed Project file
  8011. try:
  8012. with lzma.open(filename) as f:
  8013. file_content = f.read().decode('utf-8')
  8014. d = json.loads(file_content, object_hook=dict2obj)
  8015. except Exception as e:
  8016. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8017. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  8018. return
  8019. # Clear the current project
  8020. # # NOT THREAD SAFE # ##
  8021. if run_from_arg is True:
  8022. pass
  8023. elif cli is True:
  8024. self.delete_selection_shape()
  8025. else:
  8026. self.on_file_new()
  8027. # Project options
  8028. self.options.update(d['options'])
  8029. self.project_filename = filename
  8030. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8031. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8032. if cli is None:
  8033. self.set_screen_units(self.options["units"])
  8034. # Re create objects
  8035. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8036. for obj in d['objs']:
  8037. try:
  8038. def obj_init(obj_inst, app_inst):
  8039. obj_inst.from_dict(obj)
  8040. App.log.debug("Recreating from opened project an %s object: %s" %
  8041. (obj['kind'].capitalize(), obj['options']['name']))
  8042. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8043. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8044. if cli is None:
  8045. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8046. obj['kind'].upper(),
  8047. obj['options']['name']
  8048. )
  8049. )
  8050. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  8051. except Exception as e:
  8052. print('App.open_project() --> ' + str(e))
  8053. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8054. self.should_we_save = False
  8055. self.file_opened.emit("project", filename)
  8056. # restore autosaving after a project was loaded
  8057. self.block_autosave = False
  8058. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8059. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8060. if cli is None:
  8061. self.set_ui_title(name=self.project_filename)
  8062. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8063. def plot_all(self, fit_view=True, use_thread=True):
  8064. """
  8065. Re-generates all plots from all objects.
  8066. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8067. :param use_thread: if True will use threading for plotting the objects
  8068. :return: None
  8069. """
  8070. self.log.debug("Plot_all()")
  8071. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8072. for plot_obj in self.collection.get_list():
  8073. def worker_task(obj):
  8074. with self.proc_container.new("Plotting"):
  8075. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8076. if fit_view is True:
  8077. self.object_plotted.emit(obj)
  8078. if use_thread is True:
  8079. # Send to worker
  8080. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8081. else:
  8082. worker_task(plot_obj)
  8083. def register_folder(self, filename):
  8084. """
  8085. Register the last folder used by the app to open something
  8086. :param filename: the last folder is extracted from the filename
  8087. :return: None
  8088. """
  8089. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8090. def register_save_folder(self, filename):
  8091. """
  8092. Register the last folder used by the app to save something
  8093. :param filename: the last folder is extracted from the filename
  8094. :return: None
  8095. """
  8096. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8097. # def set_progress_bar(self, percentage, text=""):
  8098. # """
  8099. # Set a progress bar to a value (percentage)
  8100. #
  8101. # :param percentage: Value set to the progressbar
  8102. # :param text: Not used
  8103. # :return: None
  8104. # """
  8105. # self.ui.progress_bar.setValue(int(percentage))
  8106. def setup_recent_items(self):
  8107. """
  8108. Setup a dictionary with the recent files accessed, organized by type
  8109. :return:
  8110. """
  8111. icons = {
  8112. "gerber": self.resource_location + "/flatcam_icon16.png",
  8113. "excellon": self.resource_location + "/drill16.png",
  8114. 'geometry': self.resource_location + "/geometry16.png",
  8115. "cncjob": self.resource_location + "/cnc16.png",
  8116. "script": self.resource_location + "/script_new24.png",
  8117. "document": self.resource_location + "/notes16_1.png",
  8118. "project": self.resource_location + "/project16.png",
  8119. "svg": self.resource_location + "/geometry16.png",
  8120. "dxf": self.resource_location + "/dxf16.png",
  8121. "pdf": self.resource_location + "/pdf32.png",
  8122. "image": self.resource_location + "/image16.png"
  8123. }
  8124. try:
  8125. image_opener = self.image_tool.import_image
  8126. except AttributeError:
  8127. image_opener = None
  8128. openers = {
  8129. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8130. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8131. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8132. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8133. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8134. "document": None,
  8135. 'project': self.open_project,
  8136. 'svg': self.import_svg,
  8137. 'dxf': self.import_dxf,
  8138. 'image': image_opener,
  8139. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8140. }
  8141. # Open recent file for files
  8142. try:
  8143. f = open(self.data_path + '/recent.json')
  8144. except IOError:
  8145. App.log.error("Failed to load recent item list.")
  8146. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8147. return
  8148. try:
  8149. self.recent = json.load(f)
  8150. except json.errors.JSONDecodeError:
  8151. App.log.error("Failed to parse recent item list.")
  8152. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8153. f.close()
  8154. return
  8155. f.close()
  8156. # Open recent file for projects
  8157. try:
  8158. fp = open(self.data_path + '/recent_projects.json')
  8159. except IOError:
  8160. App.log.error("Failed to load recent project item list.")
  8161. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8162. return
  8163. try:
  8164. self.recent_projects = json.load(fp)
  8165. except json.errors.JSONDecodeError:
  8166. App.log.error("Failed to parse recent project item list.")
  8167. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8168. fp.close()
  8169. return
  8170. fp.close()
  8171. # Closure needed to create callbacks in a loop.
  8172. # Otherwise late binding occurs.
  8173. def make_callback(func, fname):
  8174. def opener():
  8175. func(fname)
  8176. return opener
  8177. def reset_recent_files():
  8178. # Reset menu
  8179. self.ui.recent.clear()
  8180. self.recent = []
  8181. try:
  8182. ff = open(self.data_path + '/recent.json', 'w')
  8183. except IOError:
  8184. App.log.error("Failed to open recent items file for writing.")
  8185. return
  8186. json.dump(self.recent, ff)
  8187. def reset_recent_projects():
  8188. # Reset menu
  8189. self.ui.recent_projects.clear()
  8190. self.recent_projects = []
  8191. try:
  8192. frp = open(self.data_path + '/recent_projects.json', 'w')
  8193. except IOError:
  8194. App.log.error("Failed to open recent projects items file for writing.")
  8195. return
  8196. json.dump(self.recent, frp)
  8197. # Reset menu
  8198. self.ui.recent.clear()
  8199. self.ui.recent_projects.clear()
  8200. # Create menu items for projects
  8201. for recent in self.recent_projects:
  8202. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8203. if recent['kind'] == 'project':
  8204. try:
  8205. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8206. # Attach callback
  8207. o = make_callback(openers[recent["kind"]], recent['filename'])
  8208. action.triggered.connect(o)
  8209. self.ui.recent_projects.addAction(action)
  8210. except KeyError:
  8211. App.log.error("Unsupported file type: %s" % recent["kind"])
  8212. # Last action in Recent Files menu is one that Clear the content
  8213. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8214. (_("Clear Recent projects")), self)
  8215. clear_action_proj.triggered.connect(reset_recent_projects)
  8216. self.ui.recent_projects.addSeparator()
  8217. self.ui.recent_projects.addAction(clear_action_proj)
  8218. # Create menu items for files
  8219. for recent in self.recent:
  8220. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8221. if recent['kind'] != 'project':
  8222. try:
  8223. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8224. # Attach callback
  8225. o = make_callback(openers[recent["kind"]], recent['filename'])
  8226. action.triggered.connect(o)
  8227. self.ui.recent.addAction(action)
  8228. except KeyError:
  8229. App.log.error("Unsupported file type: %s" % recent["kind"])
  8230. # Last action in Recent Files menu is one that Clear the content
  8231. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8232. (_("Clear Recent files")), self)
  8233. clear_action.triggered.connect(reset_recent_files)
  8234. self.ui.recent.addSeparator()
  8235. self.ui.recent.addAction(clear_action)
  8236. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8237. # self.ui.menufilerecent.set_submenu(recent_menu)
  8238. # recent_menu.show_all()
  8239. # self.ui.recent.show()
  8240. self.log.debug("Recent items list has been populated.")
  8241. def setup_component_editor(self):
  8242. """
  8243. Default text for the Selected tab when is not taken by the Object UI.
  8244. :return:
  8245. """
  8246. # label = QtWidgets.QLabel("Choose an item from Project")
  8247. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8248. sel_title = QtWidgets.QTextEdit(
  8249. _('<b>Shortcut Key List</b>'))
  8250. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8251. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8252. f_settings = QSettings("Open Source", "FlatCAM")
  8253. if f_settings.contains("notebook_font_size"):
  8254. fsize = f_settings.value('notebook_font_size', type=int)
  8255. else:
  8256. fsize = 12
  8257. tsize = fsize + int(fsize / 2)
  8258. # selected_text = (_('''
  8259. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8260. # </p>
  8261. #
  8262. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8263. # The normal flow when working in FlatCAM is the following:</span></p>
  8264. #
  8265. # <ol>
  8266. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8267. # file into
  8268. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8269. # even dragging and dropping the files on the GUI.<br />
  8270. # <br />
  8271. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8272. # drop of the
  8273. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8274. # &nbsp;</li>
  8275. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8276. # and then
  8277. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8278. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8279. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8280. # <br />
  8281. # If the selection of the object is done on the canvas by single click instead, and the
  8282. # <strong>SELECTED TAB</strong>
  8283. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8284. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8285. # it even if it was out of focus.<br />
  8286. # <br />
  8287. # You can change the parameters in this screen and the flow direction is like this:<br />
  8288. # <br />
  8289. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8290. # <strong> Geometry Object
  8291. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8292. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8293. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8294. # </ol>
  8295. #
  8296. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8297. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8298. # <strong>F3</strong>.</span></p>
  8299. #
  8300. # ''').format(fsize=fsize, tsize=tsize))
  8301. selected_text = '''
  8302. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8303. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8304. {s1}</span></p>
  8305. <ol>
  8306. <li><span style="font-size:{fsize}px">{s2}<br />
  8307. <br />
  8308. {s3}</span><br />
  8309. &nbsp;</li>
  8310. <li><span style="font-size:{fsize}px">{s4}<br />
  8311. &nbsp;</li>
  8312. <br />
  8313. <li><span style="font-size:{fsize}px">{s5}<br />
  8314. &nbsp;</li>
  8315. <br />
  8316. <li><span style="font-size:{fsize}px">{s6}<br />
  8317. <br />
  8318. {s7}</span></li>
  8319. </ol>
  8320. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8321. '''.format(
  8322. title=_("Selected Tab - Choose an Item from Project Tab"),
  8323. subtitle=_("Details"),
  8324. s1=_("The normal flow when working in FlatCAM is the following:"),
  8325. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8326. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8327. "files on the GUI."),
  8328. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8329. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8330. "actions offered within the app."),
  8331. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8332. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8333. "SELECTED TAB will be updated with the object properties according to its kind: "
  8334. "Gerber, Excellon, Geometry or CNCJob object."),
  8335. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8336. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8337. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8338. "the SELECTED TAB and populate it even if it was out of focus."),
  8339. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8340. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8341. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8342. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8343. "(again, done in SELECTED TAB) --> Save GCode."),
  8344. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8345. "or through its own key shortcut: <b>F3</b>."),
  8346. tsize=tsize,
  8347. fsize=fsize
  8348. )
  8349. sel_title.setText(selected_text)
  8350. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8351. self.ui.selected_scroll_area.setWidget(sel_title)
  8352. def setup_obj_classes(self):
  8353. """
  8354. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8355. class.
  8356. :return: None
  8357. """
  8358. FlatCAMObj.app = self
  8359. ObjectCollection.app = self
  8360. Gerber.app = self
  8361. Excellon.app = self
  8362. Geometry.app = self
  8363. CNCjob.app = self
  8364. FCProcess.app = self
  8365. FCProcessContainer.app = self
  8366. OptionsGroupUI.app = self
  8367. def version_check(self):
  8368. """
  8369. Checks for the latest version of the program. Alerts the
  8370. user if theirs is outdated. This method is meant to be run
  8371. in a separate thread.
  8372. :return: None
  8373. """
  8374. self.log.debug("version_check()")
  8375. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8376. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8377. App.version_url,
  8378. str(self.defaults['global_serial']),
  8379. str(self.version),
  8380. str(self.os),
  8381. urllib.parse.urlencode(self.defaults["global_stats"])
  8382. )
  8383. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8384. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8385. # urllib.parse.urlencode(self.defaults["global_stats"])
  8386. else:
  8387. # no_stats dict; just so it won't break things on website
  8388. no_ststs_dict = {}
  8389. no_ststs_dict["global_ststs"] = {}
  8390. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8391. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8392. App.log.debug("Checking for updates @ %s" % full_url)
  8393. # ## Get the data
  8394. try:
  8395. f = urllib.request.urlopen(full_url)
  8396. except Exception:
  8397. # App.log.warning("Failed checking for latest version. Could not connect.")
  8398. self.log.warning("Failed checking for latest version. Could not connect.")
  8399. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8400. return
  8401. try:
  8402. data = json.load(f)
  8403. except Exception as e:
  8404. App.log.error("Could not parse information about latest version.")
  8405. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8406. App.log.debug("json.load(): %s" % str(e))
  8407. f.close()
  8408. return
  8409. f.close()
  8410. # ## Latest version?
  8411. if self.version >= data["version"]:
  8412. App.log.debug("FlatCAM is up to date!")
  8413. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8414. return
  8415. App.log.debug("Newer version available.")
  8416. self.message.emit(
  8417. _("Newer Version Available"),
  8418. '%s<br><br>><b>%s</b><br>%s' % (
  8419. _("There is a newer version of FlatCAM available for download:"),
  8420. str(data["name"]),
  8421. str(data["message"])
  8422. ),
  8423. _("info")
  8424. )
  8425. def on_plotcanvas_setup(self, container=None):
  8426. """
  8427. This is doing the setup for the plot area (canvas).
  8428. :param container: QT Widget where to install the canvas
  8429. :return: None
  8430. """
  8431. if container:
  8432. plot_container = container
  8433. else:
  8434. plot_container = self.ui.right_layout
  8435. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8436. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8437. self.is_legacy = True
  8438. self.defaults["global_graphic_engine"] = "2D"
  8439. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8440. else:
  8441. try:
  8442. self.plotcanvas = PlotCanvas(plot_container, self)
  8443. except Exception as er:
  8444. msg_txt = traceback.format_exc()
  8445. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8446. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8447. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8448. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8449. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8450. msg += msg_txt
  8451. self.inform.emit(msg)
  8452. return 'fail'
  8453. # So it can receive key presses
  8454. self.plotcanvas.native.setFocus()
  8455. if self.is_legacy is False:
  8456. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8457. # Set the mouse button for panning
  8458. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8459. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8460. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8461. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8462. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8463. # Keys over plot enabled
  8464. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8465. if self.defaults['global_cursor_type'] == 'small':
  8466. self.app_cursor = self.plotcanvas.new_cursor()
  8467. else:
  8468. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8469. if self.ui.grid_snap_btn.isChecked():
  8470. self.app_cursor.enabled = True
  8471. else:
  8472. self.app_cursor.enabled = False
  8473. if self.is_legacy is False:
  8474. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8475. else:
  8476. # will use the default Matplotlib axes
  8477. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8478. def on_zoom_fit(self, event):
  8479. """
  8480. Callback for zoom-fit request. This can be either from the corresponding
  8481. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8482. with axes limits from the geometry bounds of all objects.
  8483. :param event: Ignored.
  8484. :return: None
  8485. """
  8486. if self.is_legacy is False:
  8487. self.plotcanvas.fit_view()
  8488. else:
  8489. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8490. width = xmax - xmin
  8491. height = ymax - ymin
  8492. xmin -= 0.05 * width
  8493. xmax += 0.05 * width
  8494. ymin -= 0.05 * height
  8495. ymax += 0.05 * height
  8496. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8497. def on_zoom_in(self):
  8498. """
  8499. Callback for zoom-in request.
  8500. :return:
  8501. """
  8502. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8503. def on_zoom_out(self):
  8504. """
  8505. Callback for zoom-out request.
  8506. :return:
  8507. """
  8508. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8509. def disable_all_plots(self):
  8510. self.defaults.report_usage("disable_all_plots()")
  8511. self.disable_plots(self.collection.get_list())
  8512. self.inform.emit('[success] %s' %
  8513. _("All plots disabled."))
  8514. def disable_other_plots(self):
  8515. self.defaults.report_usage("disable_other_plots()")
  8516. self.disable_plots(self.collection.get_non_selected())
  8517. self.inform.emit('[success] %s' %
  8518. _("All non selected plots disabled."))
  8519. def enable_all_plots(self):
  8520. self.defaults.report_usage("enable_all_plots()")
  8521. self.enable_plots(self.collection.get_list())
  8522. self.inform.emit('[success] %s' %
  8523. _("All plots enabled."))
  8524. def on_enable_sel_plots(self):
  8525. log.debug("App.on_enable_sel_plot()")
  8526. object_list = self.collection.get_selected()
  8527. self.enable_plots(objects=object_list)
  8528. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8529. def on_disable_sel_plots(self):
  8530. log.debug("App.on_disable_sel_plot()")
  8531. # self.inform.emit(_("Disabling plots ..."))
  8532. object_list = self.collection.get_selected()
  8533. self.disable_plots(objects=object_list)
  8534. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8535. def enable_plots(self, objects):
  8536. """
  8537. Enable plots
  8538. :param objects: list of Objects to be enabled
  8539. :return:
  8540. """
  8541. log.debug("Enabling plots ...")
  8542. # self.inform.emit(_("Working ..."))
  8543. for obj in objects:
  8544. if obj.options['plot'] is False:
  8545. obj.options.set_change_callback(lambda x: None)
  8546. obj.options['plot'] = True
  8547. try:
  8548. # only the Gerber obj has on_plot_cb_click() method
  8549. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8550. # disable this cb while disconnected,
  8551. # in case the operation takes time the user is not allowed to change it
  8552. obj.ui.plot_cb.setDisabled(True)
  8553. except AttributeError:
  8554. pass
  8555. obj.set_form_item("plot")
  8556. try:
  8557. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8558. obj.ui.plot_cb.setDisabled(False)
  8559. except AttributeError:
  8560. pass
  8561. obj.options.set_change_callback(obj.on_options_change)
  8562. def worker_task(objs):
  8563. with self.proc_container.new(_("Enabling plots ...")):
  8564. for plot_obj in objs:
  8565. # obj.options['plot'] = True
  8566. if isinstance(plot_obj, CNCJobObject):
  8567. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8568. else:
  8569. plot_obj.plot(visible=True)
  8570. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8571. # self.plots_updated.emit()
  8572. def disable_plots(self, objects):
  8573. """
  8574. Disables plots
  8575. :param objects: list of Objects to be disabled
  8576. :return:
  8577. """
  8578. # if no objects selected then do nothing
  8579. if not self.collection.get_selected():
  8580. return
  8581. log.debug("Disabling plots ...")
  8582. # self.inform.emit(_("Working ..."))
  8583. for obj in objects:
  8584. if obj.options['plot'] is True:
  8585. obj.options.set_change_callback(lambda x: None)
  8586. obj.options['plot'] = False
  8587. try:
  8588. # only the Gerber obj has on_plot_cb_click() method
  8589. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8590. obj.ui.plot_cb.setDisabled(True)
  8591. except AttributeError:
  8592. pass
  8593. obj.set_form_item("plot")
  8594. try:
  8595. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8596. obj.ui.plot_cb.setDisabled(False)
  8597. except AttributeError:
  8598. pass
  8599. obj.options.set_change_callback(obj.on_options_change)
  8600. try:
  8601. self.delete_selection_shape()
  8602. except Exception as e:
  8603. log.debug("App.disable_plots() --> %s" % str(e))
  8604. # self.plots_updated.emit()
  8605. def worker_task(objs):
  8606. with self.proc_container.new(_("Disabling plots ...")):
  8607. for plot_obj in objs:
  8608. # obj.options['plot'] = True
  8609. if isinstance(plot_obj, CNCJobObject):
  8610. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8611. else:
  8612. plot_obj.plot(visible=False)
  8613. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8614. def toggle_plots(self, objects):
  8615. """
  8616. Toggle plots visibility
  8617. :param objects: list of Objects for which to be toggled the visibility
  8618. :return: None
  8619. """
  8620. # if no objects selected then do nothing
  8621. if not self.collection.get_selected():
  8622. return
  8623. log.debug("Toggling plots ...")
  8624. self.inform.emit(_("Working ..."))
  8625. for obj in objects:
  8626. if obj.options['plot'] is False:
  8627. obj.options['plot'] = True
  8628. else:
  8629. obj.options['plot'] = False
  8630. self.plots_updated.emit()
  8631. def clear_plots(self):
  8632. """
  8633. Clear the plots
  8634. :return: None
  8635. """
  8636. objects = self.collection.get_list()
  8637. for obj in objects:
  8638. obj.clear(obj == objects[-1])
  8639. # Clear pool to free memory
  8640. self.clear_pool()
  8641. def on_set_color_action_triggered(self):
  8642. """
  8643. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8644. :return:
  8645. """
  8646. new_color = self.defaults['gerber_plot_fill']
  8647. clicked_action = self.sender()
  8648. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8649. act_name = clicked_action.text()
  8650. sel_obj_list = self.collection.get_selected()
  8651. if not sel_obj_list:
  8652. return
  8653. # a default value, I just chose this one
  8654. alpha_level = 'BF'
  8655. for sel_obj in sel_obj_list:
  8656. if sel_obj.kind == 'excellon':
  8657. alpha_level = str(hex(
  8658. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8659. elif sel_obj.kind == 'gerber':
  8660. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8661. elif sel_obj.kind == 'geometry':
  8662. alpha_level = 'FF'
  8663. else:
  8664. log.debug(
  8665. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8666. continue
  8667. sel_obj.alpha_level = alpha_level
  8668. if act_name == _('Red'):
  8669. new_color = '#FF0000' + alpha_level
  8670. if act_name == _('Blue'):
  8671. new_color = '#0000FF' + alpha_level
  8672. if act_name == _('Yellow'):
  8673. new_color = '#FFDF00' + alpha_level
  8674. if act_name == _('Green'):
  8675. new_color = '#00FF00' + alpha_level
  8676. if act_name == _('Purple'):
  8677. new_color = '#FF00FF' + alpha_level
  8678. if act_name == _('Brown'):
  8679. new_color = '#A52A2A' + alpha_level
  8680. if act_name == _('White'):
  8681. new_color = '#FFFFFF' + alpha_level
  8682. if act_name == _('Black'):
  8683. new_color = '#000000' + alpha_level
  8684. if act_name == _('Custom'):
  8685. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8686. c_dialog = QtWidgets.QColorDialog()
  8687. plot_fill_color = c_dialog.getColor(initial=new_color)
  8688. if plot_fill_color.isValid() is False:
  8689. return
  8690. new_color = str(plot_fill_color.name()) + alpha_level
  8691. if act_name == _("Default"):
  8692. for sel_obj in sel_obj_list:
  8693. if sel_obj.kind == 'excellon':
  8694. new_color = self.defaults['excellon_plot_fill']
  8695. new_line_color = self.defaults['excellon_plot_line']
  8696. elif sel_obj.kind == 'gerber':
  8697. new_color = self.defaults['gerber_plot_fill']
  8698. new_line_color = self.defaults['gerber_plot_line']
  8699. elif sel_obj.kind == 'geometry':
  8700. new_color = self.defaults['geometry_plot_line']
  8701. new_line_color = self.defaults['geometry_plot_line']
  8702. else:
  8703. log.debug(
  8704. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8705. continue
  8706. sel_obj.fill_color = new_color
  8707. sel_obj.outline_color = new_line_color
  8708. sel_obj.shapes.redraw(
  8709. update_colors=(new_color, new_line_color)
  8710. )
  8711. return
  8712. if act_name == _("Opacity"):
  8713. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8714. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8715. if ok_button:
  8716. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8717. for sel_obj in sel_obj_list:
  8718. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8719. sel_obj.shapes.redraw(
  8720. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8721. )
  8722. return
  8723. new_line_color = color_variant(new_color[:7], 0.7)
  8724. if act_name == _("White"):
  8725. new_line_color = color_variant("#dedede", 0.7)
  8726. for sel_obj in sel_obj_list:
  8727. sel_obj.fill_color = new_color
  8728. sel_obj.outline_color = new_line_color
  8729. sel_obj.shapes.redraw(
  8730. update_colors=(new_color, new_line_color)
  8731. )
  8732. def generate_cnc_job(self, objects):
  8733. """
  8734. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8735. :param objects: Selected objects in the Project Tab
  8736. :return:
  8737. """
  8738. self.defaults.report_usage("generate_cnc_job()")
  8739. # for obj in objects:
  8740. # obj.generatecncjob()
  8741. for obj in objects:
  8742. obj.on_generatecnc_button_click()
  8743. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8744. """
  8745. Saves the current project to the specified file.
  8746. :param filename: Name of the file in which to save.
  8747. :type filename: str
  8748. :param quit_action: if the project saving will be followed by an app quit; boolean
  8749. :param silent: if True will not display status messages
  8750. :param from_tcl True is run from Tcl Shell
  8751. :return: None
  8752. """
  8753. self.log.debug("save_project()")
  8754. self.save_in_progress = True
  8755. with self.proc_container.new(_("Saving FlatCAM Project")):
  8756. # Capture the latest changes
  8757. # Current object
  8758. try:
  8759. current_object = self.collection.get_active()
  8760. if current_object:
  8761. current_object.read_form()
  8762. except Exception as e:
  8763. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8764. pass
  8765. # Serialize the whole project
  8766. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8767. "options": self.options,
  8768. "version": self.version}
  8769. if self.defaults["global_save_compressed"] is True:
  8770. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8771. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8772. # # Write
  8773. f.write(g)
  8774. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8775. else:
  8776. # Open file
  8777. try:
  8778. f = open(filename, 'w')
  8779. except IOError:
  8780. App.log.error("Failed to open file for saving: %s", filename)
  8781. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8782. return
  8783. # Write
  8784. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8785. f.close()
  8786. # verification of the saved project
  8787. # Open and parse
  8788. try:
  8789. saved_f = open(filename, 'r')
  8790. except IOError:
  8791. if silent is False:
  8792. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8793. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8794. return
  8795. try:
  8796. saved_d = json.load(saved_f, object_hook=dict2obj)
  8797. except Exception:
  8798. if silent is False:
  8799. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8800. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8801. f.close()
  8802. return
  8803. saved_f.close()
  8804. if silent is False:
  8805. if 'version' in saved_d:
  8806. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8807. else:
  8808. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8809. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8810. tb_settings = QSettings("Open Source", "FlatCAM")
  8811. lock_state = self.ui.lock_action.isChecked()
  8812. tb_settings.setValue('toolbar_lock', lock_state)
  8813. # This will write the setting to the platform specific storage.
  8814. del tb_settings
  8815. # if quit:
  8816. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8817. # t.start()
  8818. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8819. def start_delayed_quit(self, delay, filename, should_quit=None):
  8820. """
  8821. :param delay: period of checking if project file size is more than zero; in seconds
  8822. :param filename: the name of the project file to be checked periodically for size more than zero
  8823. :param should_quit: if the task finished will be followed by an app quit; boolean
  8824. :return:
  8825. """
  8826. to_quit = should_quit
  8827. self.save_timer = QtCore.QTimer()
  8828. self.save_timer.setInterval(delay)
  8829. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8830. self.save_timer.start()
  8831. def check_project_file_size(self, filename, should_quit=None):
  8832. """
  8833. :param filename: the name of the project file to be checked periodically for size more than zero
  8834. :param should_quit: will quit the app if True; boolean
  8835. :return:
  8836. """
  8837. try:
  8838. if os.stat(filename).st_size > 0:
  8839. self.save_in_progress = False
  8840. self.save_timer.stop()
  8841. if should_quit:
  8842. self.app_quit.emit()
  8843. except Exception:
  8844. traceback.print_exc()
  8845. def save_project_auto(self):
  8846. """
  8847. Called periodically to save the project.
  8848. 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
  8849. # progress.
  8850. :return:
  8851. """
  8852. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8853. self.on_file_saveproject()
  8854. def save_project_auto_update(self):
  8855. """
  8856. Update the auto save time interval value.
  8857. :return:
  8858. """
  8859. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8860. try:
  8861. if self.autosave_timer.isActive():
  8862. self.autosave_timer.stop()
  8863. except Exception:
  8864. pass
  8865. if self.defaults['global_autosave'] is True:
  8866. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8867. self.autosave_timer.start()
  8868. def on_options_app2project(self):
  8869. """
  8870. Callback for Options->Transfer Options->App=>Project. Copies options
  8871. from application defaults to project defaults.
  8872. :return: None
  8873. """
  8874. self.defaults.report_usage("on_options_app2project")
  8875. self.preferencesUiManager.defaults_read_form()
  8876. self.options.update(self.defaults)
  8877. def toggle_shell(self):
  8878. """
  8879. Toggle shell: if is visible close it, if it is closed then open it
  8880. :return: None
  8881. """
  8882. self.defaults.report_usage("toggle_shell()")
  8883. if self.ui.shell_dock.isVisible():
  8884. self.ui.shell_dock.hide()
  8885. self.plotcanvas.native.setFocus()
  8886. else:
  8887. self.ui.shell_dock.show()
  8888. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8889. # self.shell._edit.setFocus()
  8890. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8891. # HACK - simulate a mouse click - alternative
  8892. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8893. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8894. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8895. # no_km)
  8896. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8897. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8898. # no_km)
  8899. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8900. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8901. """
  8902. Shows a message on the FlatCAM Shell
  8903. :param msg: Message to display.
  8904. :param show: Opens the shell.
  8905. :param error: Shows the message as an error.
  8906. :param warning: Shows the message as an warning.
  8907. :param success: Shows the message as an success.
  8908. :param selected: Indicate that something was selected on canvas
  8909. :return: None
  8910. """
  8911. if show:
  8912. self.ui.shell_dock.show()
  8913. try:
  8914. if error:
  8915. self.shell.append_error(msg + "\n")
  8916. elif warning:
  8917. self.shell.append_warning(msg + "\n")
  8918. elif success:
  8919. self.shell.append_success(msg + "\n")
  8920. elif selected:
  8921. self.shell.append_selected(msg + "\n")
  8922. else:
  8923. self.shell.append_output(msg + "\n")
  8924. except AttributeError:
  8925. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8926. class ArgsThread(QtCore.QObject):
  8927. open_signal = pyqtSignal(list)
  8928. start = pyqtSignal()
  8929. stop = pyqtSignal()
  8930. if sys.platform == 'win32':
  8931. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8932. else:
  8933. address = ('/tmp/testipc', 'AF_UNIX')
  8934. def __init__(self):
  8935. super(ArgsThread, self).__init__()
  8936. self.listener = None
  8937. self.thread_exit = False
  8938. self.start.connect(self.run)
  8939. self.stop.connect(self.close_listener)
  8940. def my_loop(self, address):
  8941. try:
  8942. self.listener = Listener(*address)
  8943. while self.thread_exit is False:
  8944. conn = self.listener.accept()
  8945. self.serve(conn)
  8946. except socket.error:
  8947. try:
  8948. conn = Client(*address)
  8949. conn.send(sys.argv)
  8950. conn.send('close')
  8951. # close the current instance only if there are args
  8952. if len(sys.argv) > 1:
  8953. try:
  8954. self.listener.close()
  8955. except Exception:
  8956. pass
  8957. sys.exit()
  8958. except ConnectionRefusedError:
  8959. if sys.platform == 'win32':
  8960. pass
  8961. else:
  8962. os.system('rm /tmp/testipc')
  8963. self.listener = Listener(*address)
  8964. while True:
  8965. conn = self.listener.accept()
  8966. self.serve(conn)
  8967. def serve(self, conn):
  8968. while self.thread_exit is False:
  8969. msg = conn.recv()
  8970. if msg == 'close':
  8971. break
  8972. self.open_signal.emit(msg)
  8973. conn.close()
  8974. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8975. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8976. @pyqtSlot()
  8977. def run(self):
  8978. self.my_loop(self.address)
  8979. @pyqtSlot()
  8980. def close_listener(self):
  8981. self.thread_exit = True
  8982. self.listener.close()
  8983. # end of file